5


我对使用 paramiko 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

4

2 回答 2

1

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 协议套件提供一个比 Paramiko (Fabric 本身利用的)更高级别的 Pythonic 接口。

于 2011-09-27T20:39:07.523 回答
1

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

在您的 sudo 文件中,只需添加以下内容:

默认值:your_username !requiretty

或删除默认值要求。

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

于 2013-10-23T16:43:11.063 回答