first I copied the code from here and added get_pty=sudo
in the exec_command
call.
here is my code.
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()
The issue of this code is that I get my password in the output.
[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']}
How can I overcome this issue cleanly? and if the password in stdout/stderr is a standard, can I grantee it appear in the first line of stdout and stderr?