我在使用 paramiko 的 sudo 命令时遇到了一些问题
f.ex sudo apt-get 更新
这是我的代码:
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
最佳答案
Fabric
有sudo
命令。它使用 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 :
In addition to use via the fab tool, Fabric’s components may be imported into other Python code, providing a Pythonic interface to the SSH protocol suite at a higher level than that provided by e.g. Paramiko (which Fabric itself leverages.)
关于python - 如何使用 Paramiko 制作 sudo 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4934572/