Nested SSH session with Paramiko

I managed to find a solution, but it requires a little manual work. If anyone have a better solution, please tell me.

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('first.com', username="luser", password='secret')

chan = ssh.invoke_shell()

# Ssh and wait for the password prompt.
chan.send('ssh second.com\n')
buff=""
while not buff.endswith('\'s password: '):
    resp = chan.recv(9999)
    buff += resp

# Send the password and wait for a prompt.
chan.send('secret\n')
buff=""
while not buff.endswith('some-prompt$ '):
    resp = chan.recv(9999)
    buff += resp

# Execute whatever command and wait for a prompt again.
chan.send('ls\n')
buff=""
while not buff.endswith('some-prompt$ '):
    resp = chan.recv(9999)
    buff += resp

# Now buff has the data I need.
print 'buff', buff

ssh.close()

The thing to note is that instead of this

t = ssh.get_transport()
chan = t.open_session()
chan.get_pty()

…you want this

chan = ssh.invoke_shell()

It reminds me of when I tried to write a TradeWars script when I was a kid and gave up coding for ten years. 🙂

Leave a Comment