-
Book Overview & Buying
-
Table Of Contents
Python Network Programming Techniques
By :
In the previous recipe, we saw how to first connect to a device and then execute a command. So far, we have ignored the output though.
In this recipe, you will see how to programmatically open an SSH connection, send a command, and then write the output of that command back to a file. We will use this to back up a running configuration.
Open your code editor and start by creating a file called read_out.py. Next, navigate your terminal to the same directory that you just created the read_out.py file in.
Let's start by importing the Paramiko library and create a client object as seen in the last recipe. Then execute a single command of your choice on this device and save the output:
from paramiko.client import SSHClient
SSH_USER = "<Insert your ssh user here>" SSH_PASSWORD = "<Insert your ssh password here>" SSH_HOST = "<Insert the IP/host of your device/server here>" SSH_PORT = 22 # Change this if your SSH port is different
SSHClient object, which we just imported from Paramiko:client = SSHClient()
connect method of the client object to do so. Before actually connecting, we will need to make sure that our client knows the host keys:client.load_system_host_keys() client.connect(SSH_HOST, port=SSH_PORT, username=SSH_USER, password=SSH_PASSWORD)
stdin, stdout, and stderr:CMD = "show running-config" stdin, stdout, stderr = client.exec_command(CMD)
stdout object to retrieve what the command has returned:output = stdout.readlines()
with open("backup.txt", "w") as out_file
for line in output:
out_file.write(line)python3 read_out.py
In this example, we first created a new client as seen in the previous example. We then used the exec_command() method to execute a command of our choice. We then used the returned file-like object for the standard out to read everything that our remote device printed into the standard out and write it into a file.
A file-like object in the context of Python is an object that offers the same functions as a file object. When using the open() function to create a new file object to read/write from locally, we are offered some functions such as write() or readlines(). These functions allow us to read or write from or to a file. A file-like object offers the same functions and can thus be used as if it was a remote file. We use the readlines() function on the stdout object to read everything returned – in this example, the running configuration of our device – and write it line by line to a local file.
If you prefer to just see the output of your command instead of writing it to a file, you can also use the following construct, instead of the code provided in step 7 of the recipe, to print out your entire configuration:
for line in output: print(line.strip())
The strip() method used in the preceding example will delete any unnecessary leading or trailing whitespaces.