python - 如何使用 Paramiko 制作 sudo 命令

标签 python ssh sudo paramiko

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

最佳答案

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 :

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/

相关文章:

python - 在 map 上放置更多的 folium/leaflet 元素

java - 命令完成后 JSch 会退出吗?

svn - 使用svn + ssh时,Teamcity中的参数化 check out 规则会丢弃参数

java - jsch 和运行 "sudo su -"

linux - Sudo - 等待 child ,并获取 child PID

python - 当我还需要登录时,如何使用 pywebcopy 在 Python 中下载整个网页?

python - Setupterm 找不到终端,在 Python 程序中使用 curses

java - 使用 Android 和 JSCH 获取 ConnectException : failed to connect to 192. 168.2.100(端口 22)ECONNREFUSED

linux - 更改 PATH 时找不到 Sudo 命令

python - 在 sqlalchemy 核心中使用 IFNULL