Paramiko

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()

 

Posted by Uli Köhler in Paramiko, Python

Paramiko: How to execute command and get output as string

Using exec_command() in Paramiko returns a tuple (stdin, stdout, stderr). Most of the time, you just want to read stdout and ignore stdin and stderr. You can get the output the command by using stdout.read()(returns a string) or stdout.readlines() (returns a list of lines).

Example:

stdin, stdout, stderr = ssh.exec_command("ls")
output = stdout.read()
print(output)

Also see our full example: Paramiko SSH client minimal example: How to connect to SSH server and execute command

Posted by Uli Köhler in Paramiko, Python

Paramiko SSH client: How to connect using public key authentication

This example shows how to use paramiko to connect to [email protected] using the SSH key stored in ~/.ssh/id_ed25519 using Python:

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"))

Also see our full example: Paramiko SSH client minimal example: How to connect to SSH server and execute command

Posted by Uli Köhler in Paramiko, Python

How to fix Paramiko SSHException: Server … not found in known_hosts

Problem:

When trying to connect to a SSH server using paramiko using code like

ssh = paramiko.SSHClient()
ssh.connect("192.168.1.112")

you see an error message like

SSHException: Server '192.168.1.112' not found in known_hosts

Solution:

The simplest solution is to add

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

before the call to connect():

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("192.168.1.112")

This will automatically add unknown host keys to the known hosts store. Note that this to some extent defeats the purpose of verifying host keys and you should manually verify host keys if possible. However, in many applications, there is no-one there to verify host keys in an automated process and thus this solution is more practical. Just keep in mind its security implications. 

Posted by Uli Köhler in Paramiko, Python