title: Nested SSH session with Paramiko
body: <p>I'm rewriting a Bash script I wrote into Python. The crux of that script was</p>
  
  <pre><code>ssh -t first.com "ssh second.com very_remote_command"
  </code></pre>
  
  <p>I'm having a problem with the nested authentication with paramiko. I wasn't able to find any examples dealing with my precise situation, but I was able to find examples with <em>sudo</em> on a remote host.</p>
  
  <p><a href="http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/" rel="noreferrer">The first method</a> writes to stdin</p>
  
  <pre><code>ssh.connect('127.0.0.1', username='jesse', password='lol')
  stdin, stdout, stderr = ssh.exec_command("sudo dmesg")
  stdin.write('lol\n')
  stdin.flush()
  </code></pre>
  
  <p><a href="http://www.gossamer-threads.com/lists/python/bugs/765465" rel="noreferrer">The second</a> creates a channel and uses the socket-like <em>send</em> and <em>recv</em>.</p>
  
  <p>I was able to get <em>stdin.write</em> to work with <em>sudo</em>, but it doesn't work with <em>ssh</em> on the remote host.</p>
  
  <pre><code>import paramiko
  
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect('first.com', username='luser', password='secret')
  stdin, stdout, stderr = ssh.exec_command('ssh luser@second.com')
  stdin.write('secret')
  stdin.flush()
  print '---- out ----'
  print stdout.readlines()
  print '---- error ----'
  print stderr.readlines()
  
  ssh.close()
  </code></pre>
  
  <p>...prints...</p>
  
  <pre><code>---- out ----
  []
  ---- error ----
  ['Pseudo-terminal will not be allocated because stdin is not a terminal.\r\n', 'Permission denied, please try again.\r\n', 'Permission denied, please try again.\r\n', 'Permission denied (publickey,password,keyboard-interactive).\r\n']
  </code></pre>
  
  <p>The pseudo-terminal error reminded me of the -t flag in my original command, so I switched to the second method, using a Channel. Instead of ssh.exec_command and later, I have:</p>
  
  <pre><code>t = ssh.get_transport()
  chan = t.open_session()
  chan.get_pty()
  print '---- send ssh cmd ----'
  print chan.send('ssh luser@second.com')
  print '---- recv ----'
  print chan.recv(9999)
  chan = t.open_session()
  print '---- send password ----'
  print chan.send('secret')
  print '---- recv ----'
  print chan.recv(9999)
  </code></pre>
  
  <p>...but it prints '---- send ssh cmd ----' and just hangs until I kill the process.</p>
  
  <p>I'm new to Python and none too knowledgeable about networks. In the first case, why does sending the password work with <em>sudo</em> but not with <em>ssh</em>? Are the prompts different? Is paramiko even the right library for this?</p>