How do you execute multiple commands in a single session in Paramiko? (Python) How do you execute multiple commands in a single session in Paramiko? (Python) python python

How do you execute multiple commands in a single session in Paramiko? (Python)


Non-Interactive use cases

This is a non-interactive example... it sends cd tmp, ls and then exit.

import syssys.stderr = open('/dev/null')       # Silence silly warnings from paramikoimport paramiko as pmsys.stderr = sys.__stderr__import osclass AllowAllKeys(pm.MissingHostKeyPolicy):    def missing_host_key(self, client, hostname, key):        returnHOST = '127.0.0.1'USER = ''PASSWORD = ''client = pm.SSHClient()client.load_system_host_keys()client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))client.set_missing_host_key_policy(AllowAllKeys())client.connect(HOST, username=USER, password=PASSWORD)channel = client.invoke_shell()stdin = channel.makefile('wb')stdout = channel.makefile('rb')stdin.write('''cd tmplsexit''')print stdout.read()stdout.close()stdin.close()client.close()

Interactive use cases
If you have an interactive use case , this answer won't help... I personally would use pexpect or exscript for interactive sessions.


Try creating a command string separated by \n character. It worked for me. For. e.g. ssh.exec_command("command_1 \n command_2 \n command_3")


Strictly speaking, you can't. According to the ssh spec:

A session is a remote execution of a program. The program may be a shell, an application, a system command, or some built-in subsystem.

This means that, once the command has executed, the session is finished. You cannot execute multiple commands in one session. What you CAN do, however, is starting a remote shell (== one command), and interact with that shell through stdin etc... (think of executing a python script vs. running the interactive interpreter)