【问题标题】:How to make a sudo command using Paramiko如何使用 Paramiko 制作 sudo 命令
【发布时间】:2011-02-08 14:56:22
【问题描述】:

我在使用 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

【问题讨论】:

标签: python ssh sudo paramiko


【解决方案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`.

来自the docs

除了通过 fab 工具使用之外,Fabric 的组件还可以 导入到其他 Python 代码中,为 SSH 协议套件比 e.g. 提供的更高级别。 Paramiko(Fabric 本身利用的。)

【讨论】:

    【解决方案2】:

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

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

    默认值:your_username !requiretty

    或删除默认值要求。

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

    【讨论】: