使用 paramiko 运行 Sudo 命令 [英] Running Sudo Command with paramiko

查看:188
本文介绍了使用 paramiko 运行 Sudo 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

这是我的python代码:

and this is my python code:

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

推荐答案

首先,您是否在控制台中尝试过 ssh cdc@192.168.0.104 "sudo -S -p '' dmesg".如果它也失败了,那么您可以检查 sshd 设置和 sudoer 设置.

First of all, have you tried in console with ssh cdc@192.168.0.104 "sudo -S -p '' dmesg". If it also fails, then you might check the sshd settings and the sudoer settings.

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

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 dmesg to sudo -S -p '' dmesg.

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

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):

#!/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() 

这篇关于使用 paramiko 运行 Sudo 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆