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 sys
sys.stderr = open('/dev/null')       # Silence silly warnings from paramiko
import paramiko as pm
sys.stderr = sys.__stderr__
import os

class AllowAllKeys(pm.MissingHostKeyPolicy):
    def missing_host_key(self, client, hostname, key):
        return

HOST = '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 tmp
ls
exit
''')
print stdout.read()

stdout.close()
stdin.close()
client.close()

Interactive use cases

If you have an interactive ssh use case, paramiko can handle it… I personally would drive interactive ssh sessions with scrapli.

Listing all the ways I can think of to use paramiko interactively:

  • See nagabhushan’s answer which uses paramiko interactively
  • By default, ansible paramiko usage is configurable
  • By default, exscript ssh uses paramiko
  • By default, netmiko ssh uses paramiko
  • By default, scrapli ssh uses paramiko

I might have missed some libraries that use paramiko, but it should be clear that paramiko is used quite extensively by python libraries that control ssh sessions.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)