Python 使用 paramiko 运行 Sudo 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22587855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:13:43  来源:igfitidea点击:

Running Sudo Command with paramiko

pythonsocketssshparamiko

提问by user3176971

I am trying to execute a sudo command on a remote machine using python-paramiko, when I execute the command, I bind it with 3 streams, and I use the input stream to pass the password, but it doesn't work, this is the traceback result:

我正在尝试使用python-paramiko在远程机器上执行sudo命令,当我执行命令时,我将它与3个流绑定,并使用输入流传​​递密码,但它不起作用,这是回溯结果:

Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/paramiko/file.py", line 314, in write
self._write_all(data)
File "/usr/local/lib/python2.7/dist-packages/paramiko/file.py", line 439, in _write_all
count = self._write(data)
File "/usr/local/lib/python2.7/dist-packages/paramiko/channel.py", line 1263,in _write
self.channel.sendall(data)
File "/usr/local/lib/python2.7/dist-packages/paramiko/channel.py", line 796, in sendall
raise socket.error('Socket is closed')
error: Socket is closed

and this is my python code:

这是我的python代码:

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.0.104', username='cdc',password='123456')
stdin, stdout, stderr = ssh.exec_command("sudo dmesg")
stdin.write("123456\n")
stdin.flush()
print stdout.readlines()
ssh.close()

Any help? Thanks in advance

有什么帮助吗?提前致谢

回答by stanleyxu2005

First of all, have you tried in console with ssh [email protected] "sudo -S -p '' dmesg". If it also fails, then you might check the sshdsettings and the sudoersettings.

首先,您是否尝试过在控制台中使用ssh [email protected] "sudo -S -p '' dmesg". 如果它也失败了,那么您可能会检查sshd设置和sudoer设置。

If it works well, please add some echo between lines, so that we can know exactly when the exception was thrown. I highly doubt that you should change sudo dmesgto sudo -S -p '' dmesg.

如果运行良好,请在行之间添加一些 echo,以便我们可以准确知道何时抛出异常。我非常怀疑您是否应该更改sudo dmesgsudo -S -p '' dmesg.

You might also try my wrapper of paramiko. I can use it smoothly to access any CentOS/SuSE node and perform any commands (w/wo sudo privilege):

你也可以试试我的 paramiko 包装器。我可以流畅地使用它来访问任何 CentOS/SuSE 节点并执行任何命令(w/wo sudo 权限):

#!/usr/bin/python

from StringIO import StringIO
import paramiko 

class SshClient:
    "A wrapper of paramiko.SSHClient"
    TIMEOUT = 4

    def __init__(self, host, port, username, password, key=None, passphrase=None):
        self.username = username
        self.password = password
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if key is not None:
            key = paramiko.RSAKey.from_private_key(StringIO(key), password=passphrase)
        self.client.connect(host, port, username=username, password=password, pkey=key, timeout=self.TIMEOUT)

    def close(self):
        if self.client is not None:
            self.client.close()
            self.client = None

    def execute(self, command, sudo=False):
        feed_password = False
        if sudo and self.username != "root":
            command = "sudo -S -p '' %s" % command
            feed_password = self.password is not None and len(self.password) > 0
        stdin, stdout, stderr = self.client.exec_command(command)
        if feed_password:
            stdin.write(self.password + "\n")
            stdin.flush()
        return {'out': stdout.readlines(), 
                'err': stderr.readlines(),
                'retval': stdout.channel.recv_exit_status()}

if __name__ == "__main__":
    client = SshClient(host='host', port=22, username='username', password='password') 
    try:
       ret = client.execute('dmesg', sudo=True)
       print "  ".join(ret["out"]), "  E ".join(ret["err"]), ret["retval"]
    finally:
      client.close() 

回答by gloomy.penguin

I know this question is kind of old but I was wanting to use sudo and paramiko together, too. It took me a while to figure out this solution. It may not work for everyone but I figured it was worth adding.

我知道这个问题有点老了,但我也想同时使用 sudo 和 paramiko。我花了一段时间才想出这个解决方案。它可能并不适合所有人,但我认为值得添加。

def ssh_handler(hostname, username=USER, password=PASS, command=CMD): 
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname,
                username=username,
                password=password) 

    stdin, stdout, stderr = ssh.exec_command(prepare_command(command))
    # stdin.write(password+'\n')  

    response = stdout.read()   
    ssh.close()
    print response


def prepare_command(command):  
    if (not isinstance(command, basestring)): 
        command = ' ; '.join(command)  
    command = command.replace('"','\"') 
    command = 'sudo -s -- " '+command+' " \n'
    return command


# kind of a dumb example but you get the point 
mycmd = []; 
mycmd.append('cd /dir/this/user/doesnt/have/access/to')
mycmd.append('ls -las')
mycmd.append('cat file_in_dir.txt')

ssh_handler(server, command=mycmd)

回答by AlexS

Im sorry i dont have time for details answer but i was able to implement sudo commands on paramiko using thisadvise

对不起,我没有时间详细回答,但我能够使用建议在 paramiko 上实施 sudo 命令

#!/usr/bin/env python
import paramiko
l_password = "yourpassword"
l_host = "yourhost"
l_user = "yourusername"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(l_host, username=l_user, password=l_password)    
transport = ssh.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
#for testing purposes we want to force sudo to always to ask for password. because of that we use "-k" key
session.exec_command("sudo -k dmesg")
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
#you have to check if you really need to send password here 
stdin.write(l_password +'\n')
stdin.flush()
for line in stdout.read().splitlines():        
    print 'host: %s: %s' % (l_host, line)