Use the same SSH object to issue "exec_command()" multiple times in Paramiko
Question: I want to use the same SSH object to issue `exec_command()` multiple times in
Paramiko module in Python.

The objective is to get output from the same session.

Is there a way to do it? The `exec_command()` closes channel once it completes
executing a command and thereafter a new ssh object is needed to execute a
following command .. but the sessions will differ which I do not want.

**Code**

    
    
    import os, sys, 
    import connectlibs as ssh
    s = ssh.connect("xxx.xx.xx.xxx", "Admin", "Admin")
    channel = s.invoke_shell()
    channel.send("net use F: \\\\xyz.xy.xc.xa\\dir\n")
    >>>32
    channel.send("net use")
    >>>7
    channel.recv(500)
    'Last login: Tue Jun  2 23:52:29 2015 from xxx.xx.xx.xx\r\r\n\x1b]0;~\x07\r\r\n\x1b[32mAdmin@WIN \x1b[33m~\x1b[0m\r\r\n$ net use F: \\\\xyz.xy.xc.xa\\dir\r\nSystem error 67 has occurred.\r\r\n\r\r\nThe network name cannot be found.\r\r\n\r\r\n\x1b]0;~\x07\r\r\n\x1b[32mAdmin@WIN \x1b[33m~\x1b[0m\r\r\n$ net use'
    >>> 
    


Answer: An SSH session can have multiple channels indeed (but [Paramiko possibly does
not support it](http://stackoverflow.com/a/19867108/850848)).

But by a session you seem to imagine a "shell session". But that's not what
the SSH session is. A channel is actually what corresponds to a "shell
session".

In other words, even if you could open multiple "exec" channels with Paramiko
over the same SSH connection (session) and call `exec_command` on these, the
commands get executed in a _different shell session_. So it won't help you.

* * *

You can test this with PuTTY SSH client. The latest version (0.64) supports
[connection
sharing](http://the.earth.li/~sgtatham/putty/0.64/htmldoc/Chapter4.html#config-
ssh-sharing), what basically means that you can have more PuTTY windows (each
using its own channel) over a single SSH connection/session. If you execute a
command in one PuTTY window, and the commands changes an environment (line an
environment variable or a current working directory), the change won't get
reflected to the other PuTTY window, even if they share the same SSH
connection.

* * *

So you need to execute the commands in a one channel. Depending on your needs
(which are still not clear), you need to use "exec" or "shell" channel.

In either case you will have troubles determining where output of one command
ends and output of other command starts as they share the same "stream".

You can solve that by inserting an unique separator (string) in between and
search for it in the channel output stream.

    
    
    channel = ssh.invoke_shell()
    channel.send('ls\n')
    channel.send('echo unique-string-separating-output-of-the-commands\n')
    channel.send('pwd\n')
    

