如何用Paramiko执行sudo命令

5 投票
2 回答
7402 浏览
提问于 2025-04-16 11:27

我在使用paramiko执行带有sudo的命令时遇到了一些问题,比如说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

2 个回答

1

我之前也遇到过同样的问题,我是这样解决的:

在你的sudo文件里,添加这一行:

Defaults:你的用户名 !requiretty

或者直接删除 Defaults requiretty 这一行。

另外,确保你的用户有权限用sudo来执行这个命令。

1

Fabric 有一个叫做 sudo 的命令。它使用 Paramiko 来进行 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 本身也依赖这个库)提供的接口要更 Python 化。

撰写回答