paramiko + sudo,在stdout / stderr中返回我的密码

时间:2015-12-15 08:37:16

标签: python passwords sudo paramiko

首先我复制了来自here的代码,并在get_pty=sudo来电中添加了exec_command

这是我的代码。

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, get_pty=sudo)
        if feed_password and not stdout.channel.closed:
            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='xxxxx', port=22, username='zhifan2', password='zhifan')
    try:
       ret = client.execute('id', sudo=True)
       print (ret)
    finally:
      client.close()

此代码的问题是我在输出中获取了密码。

[zhifan2@host86 ~]$ python sudo.py
{'retval': 0, 'err': [], 'out': [u'**zhifan\r\n**', u'\r\n', u'uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)\r\n']}

我怎样才能彻底克服这个问题? 如果stdout / stderr中的密码是标准的,我可以将它显示在stdout和stderr的第一行吗?

0 个答案:

没有答案
相关问题