paramiko transport and invoke_shell

greg.szewski at gmail.com greg.szewski at gmail.com
Wed Jan 20 14:06:51 EST 2016


Hi,
I've found below code which almost suits my needs but I need to interact via shell so can do stuff like sudo su - user then when sudo asks for password I need to send password and working as user run next commands . I'm pretty sure invoke_shell method is the solution but my programing skills are realy low . So maybe You will help def method executeShell method for below code .


import paramiko as ssh

class SSHTool():
def __init__(self, host, user, auth,
via=None, via_user=None, via_auth=None):
if via:
t0 = ssh.Transport(via)
t0.start_client()
t0.auth_password(via_user, via_auth)
# setup forwarding from 127.0.0.1: to |host|
channel = t0.open_channel('direct-tcpip', host, ('127.0.0.1', 0))
self.transport = ssh.Transport(channel)
else:
self.transport = ssh.Transport(host)
self.transport.start_client()
self.transport.auth_password(user, auth)

def run(self, cmd):
ch = self.transport.open_session()
ch.set_combine_stderr(True)
ch.exec_command(cmd)
retcode = ch.recv_exit_status()
buf = ''
while ch.recv_ready():
buf += ch.recv(1024)
return (buf, retcode)

def run_in_shell()
...
...

# The example below is equivalent to
# $ ssh 10.10.10.10 ssh 192.168.1.1 uname -a
# The code above works as if these 2 commands were executed:
# $ ssh -L :192.168.1.1:22 10.10.10.10
# $ ssh 127.0.0.1: uname -a
host = ('192.168.1.1', 22)
via_host = ('10.10.10.10', 22)

ssht = SSHTool(host, 'user1', 'pass1',
via=via_host, via_user='user2', via_auth='pass2')

print ssht.run('uname -a')
print ssht.run_in_shell('sudo su - user')
ssht.run_in_shell('password_for_above')
print ssht.run_in_shell('id')
# above id should return user

Regards
Greg






More information about the Python-list mailing list