繁体   English   中英

如何使用Paramiko制作sudo命令

[英]How to make a sudo command using Paramiko

我在使用paramiko的sudo命令时遇到了一些问题
f.ex sudo apt-get update

这是我的代码:

try:
    import paramiko
except:
    try:
        import paramiko
    except:
        print "There was an error with the paramiko module"
cmd = "sudo apt-get update"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    ssh.connect("ip",username="lexel",password="password")
    print "succesfully conected"
except:
    print "There was an Error conecting"
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('password\n')
stdin.flush()
print stderr.readlines()
print stdout.readlines()

这是一个快速代码。 我知道我需要添加sys.exit(1)以及所有这些,但这仅仅是为了演示

我用这个作为参考: Jessenoller.com

我遇到了同样的问题,我解决了这个问题:

在你的sudo文件中,只需添加:

默认值:your_username!requiretty

或删除默认值requiretty。

还要确保您的用户有权使用sudo运行该命令。

Fabricsudo命令。 它使用Paramico进行ssh连接。 你的代码是:

#fabfile.py
from fabric.api import run, sudo

def update():
    """Run `sudo apt-get update`.

    lorem ipsum
    """
    sudo("apt-get update")

def hostname():
    """Run `hostname`"""
    run("hostname")

用法:

$ fab update -H example.com
[example.com] Executing task 'update'
[example.com] sudo: apt-get update
...snip...
[example.com] out: Reading package lists... Done
[example.com] out: 

Done.
Disconnecting from example.com... done.

$ fab --display update
Displaying detailed information for task 'update':

    Run `sudo apt-get update`.

        lorem ipsum

$ fab --list
Available commands:

    hostname  Run `hostname`
    update    Run `sudo apt-get update`.

来自文档

除了通过fab工具使用外,Fabric的组件可以导入到其他Python代码中,为SSH协议套件提供Pythonic接口,其级别高于例如Paramiko(Fabric本身利用的)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM