Paramiko SSH client minimal example: How to connect to SSH server and execute command

This example shows how to use paramiko to connect to [email protected] using the SSH key stored in ~/.ssh/id_ed25519, execute the command ls and print its output. Since paramiko is a pure Python implementation of SSH, this does not require SSH clients to be installed.

import os.path
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("192.168.1.112", username="user",
            key_filename=os.path.join(os.path.expanduser('~'), ".ssh", "id_ed25519"))

# Example command:
stdin, stdout, stderr = ssh.exec_command("ls")
output = stdout.read()
print(output)

# Cleanup
ssh.close()