Python: Network Automation with Paramiko

1 minute read

Updated:

Paramiko

Using telnet in a lab environment for practice or in a fully isolated private network is recommended, but in a production or public network, telnet is vulnerable to cyber attack.

To overcome this anomaly, network engineers use ssh. SSH is a network protocol that is widely used to access and manage a device remotely and a major protocol to access the network devices and servers over the internet. To configure ssh on device’s see telnetlib script in previous lab.

To automate networking devices via SSH, we will using Paramiko. Paramiko is a pure-Python [1] (2.7, 3.4+) implementation of the SSHv2 protocol [2], providing both client and server functionality.

Paramiko’s documentation https://docs.paramiko.org/en/stable/

To install paramiko simply use pip for installation.

pip install paramiko

We will use our topology as below:

picture

Lab Configuration same as previous.

Example of Paramiko

Below is the python code for achieving our task. Write the code using a nano editor as exe_01.py.

import paramiko, time

# The first four lines create an instance of the SSHClient class from Paramiko
connection = paramiko.SSHClient()
# Sets the policy that the client should use regarding keys
connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# The next few lines invoke a new interactive shell from the connection
connection.connect('192.168.10.10', username='admin', password='cisco', look_for_keys=False, allow_agent=False)
new_connection = connection.invoke_shell()

# Send command to the remote device
new_connection.send("sh ip int bri\n")
# Wait for the command to be finished on the remote device before retrieving the output
time.sleep(3)

'''if you did not clear out the received buffer? 
The output would just keep on filling up the buffer and would overwrite it.
For consistency of the output, we will retrieve the output from the 
buffer each time we execute a command.'''

output = new_connection.recv(5000)
print(output.decode())
# Close the remote connection
new_connection.close()

More on Github

Comments