Script: Cisco Device configuration backup with Python

If you are a network admin or network engineer then you would know the pain of configuration backups.Suddenly one day you will see one of your router died without  any prior issues or errors. And guess what, this is the remote site that you have not logged in since last 6 months. Since this is just an ignored part of your network you do not get chance often to look into it and hence you are not aware of much of the configurations that was done here while the installation. Now, you got the dead router replaced and wondering what to put in configurations???? Well without any backups, you are left with  no options but to call the remote store manager/local IT or random people who do not even know what router looks like 😀 :D. Now you need to talk with them to understand the kind of setup so that you can come up with a working config BUT this process can be as difficult as explaining AI (Artificial intelligence) to your grandma 🙂

Recently I was talking with few of my network engineer friends about their time spent on the job in last one month. You wont believe that mostly all of them have spend good amount of time in following small tasks like below.

  1. Trying to recover a forgotten password
  2. Config lost as the config was not properly saved
  3. No backup taken hence re-configuring the router from scratch

Alright, so we know that this is an issue but how to fix it ? Well there are many network monitoring tools available in the market which are available to do all these tasks as per configured schedules. But what if you come across a situation where you do not have those tools or the money to buy it…….. and still need to  take backup of a network devices at scheduled manner. So the challenge is to not to rely on commercially available tools but to use whatever you have to trigger automatic backup and challenges help you evolve.

This blog is going to help you in that,  In fact this blog will help you to develop a full fledged network management tool with the help of python with which you can do SNMP/Backups/Configurations and many other things. So please do not forget to follow the blog 🙂

Before you begin, you need to have following in place.

  1. Download the code given at the end of this blog and save it on your PC.
  2. Create a text file which has list of host IP address which needs to be backed up.
  3. Make sure to put correct location of the host file in the python script.
  4. All the routers should have SSH enabled, you can also do this with telnet but this blog talks about SSH.

Following is the script and explanation to take router backup.

 

import sys
import time
import paramiko 
import os
import cmd
import datetime

now = datetime.datetime.now()
user = raw_input("Enter username:")
password = raw_input("Enter Paswd:")
enable_password = raw_input("Enter enable pswd:")
port=22

 

In the above piece of the code I have used paramiko python library for ssh here I have imported the necessary libraries and declaring some of the important variables which is needed to login into the router.

 

f0 = open('cisco.txt')
for ip in f0.readlines():
ip = ip.strip()
filename_prefix ='/Users/shambhu/Documents' + ip

 

In the above piece of the code I am reading the file f0 which is placed in the same directory where my python code is residing and extracting the IP addresses of the hosts for which I need to run the code.

 

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port, user, password, look_for_keys=False)
chan = ssh.invoke_shell()
time.sleep(2)

 

In the above piece of code I am assigning the assigned variables (username, password,enable password , host IP and port number) to the ssh socket and initiating the connection. Once the connection is initiated then I will be invoking the channel for router shell to send command and read the outputs.

 

chan.send('enable\n')
chan.send(enable_password +'\n')
time.sleep(1)
chan.send('term len 0\n')
time.sleep(1)
chan.send('sh run\n')
time.sleep(20)
output = chan.recv(999999)

 

In the above piece of the code I am just sending some commands to the router in sleep time intervals. Like “term lengh 0 “, “show run” etc.

 

Note : Make sure that you put proper sleep time after the command run to collect complete output of that command, some commands takes time to run like show tech, you should have more sleep time for the script for commands like that.

 

filename = "%s_%.2i%.2i%i_%.2i%.2i%.2i" % (ip,now.year,now.month,now.day,now.hour,now.minute,now.second)
f1 = open(filename, 'a')
f1.write(output.decode("utf-8") )
f1.close()
ssh.close() 
f0.close()

 

In the above piece of code I am just saving the configuration and closing the files which are opened in the early pieces of the code.

Following is the complete script.

import sys
import time
import paramiko 
import os
import cmd
import datetime

now = datetime.datetime.now()
user = raw_input("Enter username:")
password = raw_input("Enter Paswd:")
enable_password = raw_input("Enter enable pswd:")
port=22
f0 = open('cisco.txt')
for ip in f0.readlines():
       ip = ip.strip()
       filename_prefix ='/Users/shambhu/Documents' + ip 
       ssh = paramiko.SSHClient()
       ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
       ssh.connect(ip,port, user, password, look_for_keys=False)
       chan = ssh.invoke_shell()
       time.sleep(2)
       chan.send('enable\n')
       chan.send(enable_password +'\n')
       time.sleep(1)
       chan.send('term len 0\n')
       time.sleep(1)
       chan.send('sh run\n')
       time.sleep(20)
       output = chan.recv(999999)
       filename = "%s_%.2i%.2i%i_%.2i%.2i%.2i" % (ip,now.year,now.month,now.day,now.hour,now.minute,now.second)
       f1 = open(filename, 'a')
       f1.write(output.decode("utf-8") )
       f1.close()
       ssh.close() 
       f0.close()

 

Steps to run the backup (Manual):

  1. Run the python code on your PC. The code will fetch all the IP addresses from the text file that you have saved and take backup.
  2. Verify the location given in the code (/Users/shambhu/Documents in my case ) for the backup file.

Steps to run scheduled backup (Automatic):

  1. For this first and foremost thing is to put the username and password in the script so that you do not need to put it manually on each execution as in previous code.
  2. Schedule the script to run at a particular time of the day. In windows you can do it with scheduler. On Macbook I have done it with crontab. There is an even simpler way or daily, weekly and monthly schedule on MAC. All you need to do is to copy your script at Daily/Weekly/Monthly folder at the following directory :

 

bash-3.2# cd /etc/periodic/
bash-3.2# ls
daily monthly weekly
bash-3.2#

 

The scheduled script looks like this.

import sys
import time
import paramiko 
import os
import cmd
import datetime

now = datetime.datetime.now()
# mention username and password 
user = "cisco" 
password = "cisco"
enable_password = "cisco"
# mention username and password 
port=22
f0 = open('cisco_routerswitch.txt')
for ip in f0.readlines():
      ip = ip.strip()
      filename_prefix ='/Users/shambhu/Documents' + ip 
      ssh = paramiko.SSHClient()
      ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
      ssh.connect(ip,port, user, password, look_for_keys=False)
      chan = ssh.invoke_shell()
      time.sleep(2)
      chan.send('enable\n')
      chan.send(enable_password +'\n')
      time.sleep(1)
      chan.send('term len 0\n')
      time.sleep(1)
      chan.send('sh run\n')
      time.sleep(20)
      output = chan.recv(999999)
      filename = "%s_%.2i%.2i%i_%.2i%.2i%.2i" % (ip,now.year,now.month,now.day,now.hour,now.minute,now.second)
      f1 = open(filename, 'a')
      f1.write(output.decode("utf-8") )
      f1.close()
      ssh.close() 
      f0.close()

 

So this is the whole method to do periodic backup for the Cisco devices. We have few more blogs lined up on automating daily tasks in network devices. Stay tuned.

Do not forget to rate follow this blog if you found it helpful.

 


7 thoughts on “Script: Cisco Device configuration backup with Python

    1. This is python script, if you have python installed on windows machine this should run. The scheduled backup part of the article should be done with windows scheduler.

  1. Hey, hello.
    I tried to use this script to backup one of my Routers but I haven´t made it work.
    Which version are you running on Python? For example the raw_input command I had to change it by just input.

    Regards

      1. Sorry for my late reply. I didn´t check the site in a long.
        I was running 3.8 and I made it work. My problem was that I was running the script and I was expecting to find my file/backup on the directory defined on the script but I was wrong. You will find it where you run your script. (I´m a complete newbie on programming any language but decided to start with Python. Just started 2 weeks ago) I was checking and it seems for Python 3.x the raw_input was changed by only “input”.
        Additional, the line filename_prefix is not saving the file on the directory I put. May be another difference with Python 3.x

Leave a Reply