Python SSH Client - Paramiko. SSH with Python.

Paramiko - A Python SSH Library

"Paramiko" is a combination of the Esperanto words for "paranoid" and "friend". It's a module for Python that implements the SSH2 protocol for secure connections to remote machines.

Paramiko is wildly popular in the Python community and is used as the SSH module of choice in popular tools such as Ansible.

Installing Paramiko

Installing Paramiko is easy, just install it via pip.

 Terminal
pip install paramiko

Lab 1 - Basic SSH Connectivity and sending a command using Paramiko.

In the video, I go over how to import SSH keys, connect to clients with Paramiko, and how to run commands.

 main.py
from paramiko import SSHClient, AutoAddPolicy
from rich import print, pretty, inspect
pretty.install()

client = SSHClient()
#LOAD HOST KEYS
#client.load_host_keys('~/.ssh/known_hosts')
client.load_host_keys('C:/Users/brad/.ssh/known_hosts')
client.load_system_host_keys()

#Known_host policy
client.set_missing_host_key_policy(AutoAddPolicy())


#client.connect('10.1.1.92', username='root', password='password1')
client.connect('10.1.1.83', username='root')


# Run a command (execute PHP interpreter)
#client.exec_command('hostname')
stdin, stdout, stderr = client.exec_command('hostname')
print(type(stdin))
print(type(stdout))
print(type(stderr))

# Optionally, send data via STDIN, and shutdown when done
stdin.write('Hello world')
stdin.channel.shutdown_write()

# Print output of command. Will wait for command to finish.
print(f'STDOUT: {stdout.read().decode("utf8")}')
print(f'STDERR: {stderr.read().decode("utf8")}')

# Get return code from command (0 is default for success)
print(f'Return code: {stdout.channel.recv_exit_status()}')

# Because they are file objects, they need to be closed
stdin.close()
stdout.close()
stderr.close()

# Close the client itself
client.close()

Lab 2 - Automating SSH commands to multiple hosts

In the video, I go over a script in which it connects to a list of hosts and runs a command.

 get_hostnames.py
from paramiko import SSHClient, AutoAddPolicy

hosts = ['10.1.1.83', 
         '10.1.1.84', 
         '10.1.1.85']

for host in hosts:
    client = SSHClient()
    client.load_host_keys('C:/Users/brad/.ssh/known_hosts')
    client.set_missing_host_key_policy(AutoAddPolicy())
    client.load_system_host_keys()
    client.connect(host, username='root')

    # Run a command (execute PHP interpreter)
    #client.exec_command('hostname')
    stdin, stdout, stderr = client.exec_command('uname -a')

    if stdout.channel.recv_exit_status() == 0:
        print(f'STDOUT: {stdout.read().decode("utf8")}')
    else:
        print(f'STDERR: {stderr.read().decode("utf8")}')

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