Paramiko
Introduction
Paramiko is a Python (2.7, 3.4+) implementation of the SSHv2 protocol, providing both client-side and server-side functionality.
While it uses the Python C extension for low-level cryptography (Cryptography), Paramiko itself is a pure Python interface around the networking concepts of SSH.
Documentation for the Paramiko library:
docs.paramiko.org
Example
The simplest example of connecting to 192.168.56.2 with the user andrey and the password olegovich
#!/usr/bin/env python
import time
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(
'192.168.56.2',
username='andrey',
password='olegovich'
)
command = 'ls'
(stdin, stdout, stderr) = client.exec_command(command)
time.sleep(1.0)
for line in stdout.readlines():
print(line, end = '')
client.close()
Note the following
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
This means that the presence of the host keys of the host you are connecting to in the file
known_hosts
will not be checked.
This is insecure and can only be used when connecting to a host that you fully
trust.
You can study the details in the article
SSH
time.sleep(1.0)
This is a straightforward way to avoid the error AttributeError: 'NoneType' object has no attribute 'time'
Objects
Let us figure out what is what
client = paramiko.SSHClient()
print(type(client))
<class 'paramiko.client.SSHClient'>
(stdin, stdout, stderr) = client.exec_command(command)
print(type(stdin))
print(type(stdout))
print(type(stderr))
<class 'paramiko.channel.ChannelStdinFile'> <class 'paramiko.channel.ChannelFile'> <class 'paramiko.channel.ChannelStderrFile'>
Article author: Andrei Olegovich