In a previous article, we looked at how to leverage the Python Module Paramiko to connect to Cisco routers and switches via SSH and execute commands. In this article, we will build on that knowledge and build a Cisco config backup system of all our devices on a schedule. You can also use this information to push common updates to all your devices, such as updating a syslog server entry, SNMP server, or any other commands you may need to send to all devices.
Latest posts by John Kull (see all)

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.

Networking with Cisco

Networking with Cisco

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!

Conclusion

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.

avatar
8 Comments
  1. Georg Pauwen 6 months ago

    Hello ! I am trying to use the script, but I am getting an error:

    –> Line has invalid autocommand “show run”

    Not really sure where this goes wrong, or how to debug…do you have any ideas ?

  2. Author
    John Kull 6 months ago

    Can you show me more of the code where you get this error? What type of device are you connecting too?

    • Georg Pauwen 6 months ago

      Hello John,

      thanks for your reply. I am using the code below, which I think is pretty much identical to the one in your article. The devices are Cisco routers and switches. Do you have a sample of the text file that is used in the devicelist ? I just put each IP address on a new line, maybe that is the wrong format ?

      # import modules needed and set up ssh connection parameters
      import paramiko
      import datetime
      user = ‘admin’
      secret = ‘admin’
      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 = “F:\\Automation\\cisco automation\\”
      outfilepath = “F:\\Automation\\cisco automation\\”
      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()

    • Georg Pauwen 6 months ago

      Hello John,

      thanks for replying. I am using the code below, which I think is identical to the one in your article. I wonder if there is any special formatting used for the devicelist textfile (I simply put each IP address on a new line) ?

      # import modules needed and set up ssh connection parameters
      import paramiko
      import datetime
      user = ‘admin’
      secret = ‘admin’
      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 = “F:\\Automation\\cisco automation\\”
      outfilepath = “F:\\Automation\\cisco automation\\”
      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()

  3. Author
    John Kull 6 months ago

    Is the user account on the CISCO device you are using have level 15 privileges? Since the error seems to be the show run command it might be the user account does not have the correct privilege to execute the show run command?

    avatar
  4. Kashif 4 months ago

    Hi John,

    I need your help regarding the code with TFTP as you were added TFTP commands in last .
    Can you share the code with TFTP after editing i want to take configuration backup in config file format like TFTP take configuration backup and put this backup on TFTP directory.
    Appreciate if you can help me.

    Regards,
    Kashif

  5. Arun Kumar 3 months ago

    Hi John,

    Can we add multiple show commands in this script, we need to execute two more commands to while taking backup. Can help me with that

    #show run
    #show ip interface brief
    #show env all

  6. john trinh 6 days ago

    Hi John,

    Can we add multiple show commands in this script, we need to execute two more commands to while taking backup. Can help me with that

Leave a reply

Please enclose code in pre tags

Your email address will not be published.

*

© 4sysops 2006 - 2023

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account