preface

In daily automatic operation and maintenance (O&M) scenarios, you often need to connect to Linux devices for interactive operations, such as collecting specific system information, device health status, and background process tasks. According to the current development scenarios, three modules are mainly used: Paramiko, Netmiko, and NapALM. These modules can be built into the device interaction layer at the bottom of the automation operation and maintenance framework. Starting with the Paramiko module, this paper will spend three articles to sort out the relationship between these three modules and what different business scenarios they are applicable to.

Paramiko

Applicable scenario

The Paramiko module is a pure Python implementation of the SSH2 protocol and provides both client and server functionality. The SSH client is used to connect to the device, run remote shell commands or transfer files.

The core function

Paramiko contains two core components: SSHClient and SFTPClient. The SSHClient facilitates REMOTE SSH connections, and the SFTPClient transfers SFTP files over THE SFTP protocol.

Remote connection mode:

  1. Connect based on username and password;
  2. Connection based on public key;

SSHClient

SSHClient is similar to the SSH command in Linux. It encapsulates SSH sessions. This class encapsulates Transport, Channel, and methods established by SFTPClient (open_sftp), and is usually used to execute remote commands.

Use the sample

  • Based on username and password:
import paramiko

ssh = paramiko.SSHClient()             
Create an SSH object
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# allow connections to hosts not in the know_hosts file
ssh.connect(hostname='IP address', port=22, username='root', password='@ 999')
# Connect to server
stdin, stdout, stderr = ssh.exec_command('ls')
# execute command
result = stdout.read()
Get the command result
print(result)

ssh.close()
# close the connection
Copy the code
  • Public key:
import paramiko
 
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
Create an SSH object
ssh = paramiko.SSHClient()
# allow connections to hosts not in the know_hosts file
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to server
ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', key=private_key)
# execute command
stdin, stdout, stderr = ssh.exec_command('df')
Get the command result
result = stdout.read()
# close the connection
ssh.close()
Copy the code

SFTPClient

The SFTPClient class enables you to use the SFTP protocol based on SSH. To open an SFTP session, a SFTPClient session object is created by successfully creating the SSHClient object. Operation Session objects upload and download files.

Example:

  • Upload and download based on user name and password:
import paramiko

transport = paramiko.Transport(('ip'.22))
transport.connect(username='root', password='SHIzhiming@999')

sftp = paramiko.SFTPClient.from_transport(transport)
Upload up.py to the server
# sftp.put('up.py', 'up.py')

Download the server files to the local directory
sftp.get('up9.py'.'up_9.py')

transport.close()
Copy the code
  • Based on public key :(similar to SSHClient)
import paramiko
 
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
 
transport = paramiko.Transport(('hostname'.22))
transport.connect(username='GSuser', pkey=private_key )
 
sftp = paramiko.SFTPClient.from_transport(transport)

# upload location.py to server/TMP /test.py
sftp.put('/tmp/location.py'.'/tmp/test.py')

Download remove_path to local_path
sftp.get('remove_path'.'local_path')
 
transport.close()
Copy the code

Transport

Tranport is convenient. You can create multiple channels and then multiplex them in a single session. You can also create a single channel to bind different clients.

Example:

with Transport((hostname, port)) as transport:
    transport.connect(username=username, password=password)

    ssh_client = SSHClient()
    ssh_client._transport = transport
    command = "free -m"
    stdin, stdout, stderr = ssh_client.exec_command(command)

    result = stdout.read()
    print(result.decode("utf8"))

    sftp_client = SFTPClient.from_transport(transport)
    locate_path = "C:\\test.txt"
    remote_path = "/root/test.txt"
    sftp_client.put(locate_path, remote_path)
Copy the code

Remark:

  • Create a channel for the specified device, establish a connection, and bind the channel through SSHClient and SFTPClient to send commands and transfer files.

conclusion

In addition to the above simple tasks of login, sending commands and transferring files, on this basis, we can specifically add command interaction functions on the WEB side, etc. In daily work, we can contact batch processing devices, such as: Fabric, Ansible, is also implemented based on the Paramiko module, so paramiko understands the underlying SSH client library (and, less frequently, serves as a server); However, in the later automation development that requires compatibility with multiple devices, PARAMiko still has some limitations. If you need to design some interactive operations like Cisco, Windows, and non-UNIX devices, Paramiko does not support them, so you need to use Netmiko or Napalm. About Netmiko module, I can talk about it in detail in my next article.