- Cisco config backup with Python - Tue, Jun 14 2022
- Python module Paramiko for managing CISCO devices: Installation and usage example - Wed, Apr 27 2022
I will assume you have Python and Paramiko loaded on your PC, MAC, or Linux computer. If not, go back and look at my previous article to get these items completed.
Our script will read a list of IP addresses or host names of the devices we plan to back up from a text file you will create. If you use hostnames, be sure you have DNS entries for your devices on a local DNS server or the local hosts file of the device that will run the script. Create the text file with one device per line, and save it in a location accessible from the PC running the script.
Now, let us have a look at the script we will use. Much of this was used in the previous script. I have added comments and broken them into sections, separating the lines with a line of white space. Python ignores white space, but it makes it easier to read and understand. I have an explanation of each line after the code.
Cisco config backup Python script ^
# Backup Cisco config # by John Kull # import modules needed and set up ssh connection parameters import paramiko import datetime user = 'andmin' secret = 'P@$$w0rd!' port = 22 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # define variables time_now = datetime.datetime.now().strftime('%m_%d_%Y_%H_%M_%S') infilepath = "c:\\Users\\johnk\\Downloads\\" outfilepath = "c:\\Users\\johnk\\Downloads\\" devicelist = "device-list1.txt" # open device file input_file = open( infilepath + devicelist, "r") iplist = input_file.readlines() input_file.close() # loop through device list and execute commands for ip in iplist: ipaddr = ip.strip() ssh.connect(hostname=ipaddr, username=user, password=secret, port=port) stdin, stdout, stderr = ssh.exec_command('show run') list = stdout.readlines() outfile = open(outfilepath + ipaddr + "_" + time_now, "w") for char in list: outfile.write(char) ssh.close() outfile.close()
Here is the breakdown of each line in the script:
Lines 4–11 import Paramiko and the time module and set up the SSH parameters for Paramiko. We use the datetime function to give us a timestamp for our filename.
Lines 14–17 define some variables we will use in our script. Using variables makes our program easier to read and gives it more flexibility. I try to use variable names that make sense and make it easy to figure out what they represent. I have variables to represent the file paths to our input text file as well as the location where we will store the backup files of the Cisco config. Notice the double backslashes in the file path. This is required to escape the backslash character. Be sure to provide the full path to the file.
Lines 20–22 open the device file using the variable name and read the contents into a list called iplist that we will use in the next section of code. Line 18 closes the file once all values are read.
Line 25 begins a loop to read the values from the list, and line 26 strips any extra character, such as carriage returns or line feeds.
Lines 27–28 make the connection to the device and execute the "show run" command.
Line 29 creates a list that is used to store the content we get back from the router.
Line 30 creates the output file name by combining the variables we defined for the file path, IP address or hostname, and the current data and time. In Python, we call this concatenation of all the values. The result is a filename that looks like the image below. By rearranging these values, you can modify the names to suit your needs.
Lines 31 and 32 write the output files.
Lines 33 and 34 close the SSH connection to the device and then close the file.
If we have a look at the files created, you may notice that they have some extra characters that were generated during the process of logging in to the device. This would cause an issue if you tried to use the file directly to restore the configuration on the device. You will need to remove the extra characters before using them to restore a device. The files can be used as is for historical reference, or sections can be cut and pasted as needed.
However, there is another approach that we could take as well. All Cisco devices can copy files to a TFTP server. We can modify our script to have the devices copy their Running Config or Startup Config files via TFTP to a location defined by the TFTP server. TFTPD is the de facto standard TFTP server software used by most admins to transfer files back and forth between Cisco devices. Downloading and installing the TFTP server is beyond the scope of this article, but it is a straightforward process, and the software is free.
The command for writing to TFTP is as follows:
COPY STARTUP-CONFIG TFTP://<server IP>/filename or COPY RUNNING-CONFIG TFTP:// <server IP>/filename
One caveat to the TFTP command: it will prompt the user for the filename and IP of the server, even though we supplied them in the command. To get around this, type the following in global config mode on your Cisco device:
file prompt quiet
Now we can make a few changes to our code and have the device transfer its file to TFTP:
command = "copy startup-config tftp://192.168.200.102/" + str(ipaddr)+ "-" + time_now stdin, stdout, stderr = ssh.exec_command(command)
I created a variable for the command argument. Since the command ends up being rather long with all the variables, it was easier to create the variable and then use it in the line of code used to execute the command on the device.
The last lines of code that write an output file are no longer needed since we are writing directly to TFTP. However, you may want to leave them in for troubleshooting, as they will write out any errors that show up on the device console.
The last step in the process is scheduling your script to run. On Windows, you can use the task scheduler or create a CRON job in Linux to schedule your script to run.
Subscribe to 4sysops newsletter!
In this article, we built on previous knowledge to create a useful backup system leveraging Python with the Paramiko module and looked at two different ways for a Cisco config backup.