title: Implement an interactive shell over ssh in Python using Paramiko?
body: <p>I want to write a program (in Python 3.x on Windows 7) that executes multiple commands on a remote shell via ssh. After looking at paramikos' <code>exec_command()</code> function, I realized it's not suitable for my use case (because the channel gets closed after the command is executed), as the commands depend on environment variables (set by prior commands) and can't be concatenated into one <code>exec_command()</code> call as they are to be executed at different times in the program.</p>
  
  <p>Thus, I want to execute commands in the same channel. The next option I looked into was implementing an interactive shell using paramikos' <code>invoke_shell()</code> function:</p>
  
  <pre><code>ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect(host, username=user, password=psw, port=22)
  
  channel = ssh.invoke_shell()
  
  out = channel.recv(9999)
  
  channel.send('cd mivne_final\n')
  channel.send('ls\n')
  
  while not channel.recv_ready():
      time.sleep(3)
  
  out = channel.recv(9999)
  print(out.decode("ascii"))
  
  channel.send('cd ..\n')
  channel.send('cd or_fail\n')
  channel.send('ls\n')
  
  while not channel.recv_ready():
      time.sleep(3)
  
  out = channel.recv(9999)
  print(out.decode("ascii"))
  
  channel.send('cd ..\n')
  channel.send('cd simulator\n')
  channel.send('ls\n')
  
  while not channel.recv_ready():
      time.sleep(3)
  
  out = channel.recv(9999)
  print(out.decode("ascii"))
  
  ssh.close() 
  </code></pre>
  
  <p>There are some problems with this code:</p>
  
  <ol>
  <li>The first <code>print</code> doesn't always print the <code>ls</code> output (sometimes it is only printed on the second <code>print</code>).</li>
  <li>The first <code>cd</code> and <code>ls</code> commands are always present in the output (I get them via the <code>recv</code> command, as part of the output), while all the following <code>cd</code> and <code>ls</code> commands are printed sometimes, and sometimes they aren't.</li>
  <li>The second and third <code>cd</code> and <code>ls</code> commands (when printed) always appear before the first <code>ls</code> output.</li>
  </ol>
  
  <p>I'm confused with this "non-determinism" and would very much appreciate your help.</p>