Network Automation using Python – Part VI – Automatic backup of multiple switches
Python Backup Script
Continuing our Networking Automation using Python blog series, here is the Part 6.
Here we are explaining a simple script to take the backup of multiple Cisco switches/routers quickly. You can schedule the script using crone or job scheduler so it will automatically take daily backup without your intervention. The script will take the output of ‘sh run’ and save to the file. The file name would be device IP address + today’s date .
Please read part 1 and part 2 to get started with python and to run your first program. Please read part 4 for detailed steps on how to take an SSH session of a switch.
The script have two files
- ipfile.txt -> this file store all the device IP address
- autobackup.py -> This is the python script
How to run :
Step 1. Download the autobackup and iplist to the same folder
Step 2. Change the autobackup.txt to autobackup-cisco.py
Step 3. Open iplist.txt and save with all your device IP address which need to be backed up.
——————- advertisements ——————-
———————————————————-
Step 4. Open command prompt “CMD” and navigate to the folder where you have saved script and ‘iplist.txt’
Step 5. Run script by typing “python autobackup-cisco.py” on command prompt
Step 6. You can see the backup of device on same folder with the filename device IP address+ date
——————- advertisements ——————-
———————————————————-
Sample screenshot below.
Hope this post helped you.
You can read more posts on Network automation using Python here. Please use the comments section for any queries/suggestions .
Reference :
i tried to run the command but get this error message
D:\py>python autobackup.py
Script to take backup of devices, Please enter your credential
User name admin
Traceback (most recent call last):
File “autobackup.py”, line 23, in
device[‘username’]=input(“User name “)
File “”, line 1, in
NameError: name ‘admin’ is not defined
A little late to be adding this but I had the same issue. I found that if I used double quotes when entering my name that the script would run.
Yes, It worked when username is specified with double quotes. Thanks.
Hello, much thanks
It works super fine for Routers and switches, i wish to use this for firewall, unfortunately on firewall on login we use ssh and after login in going to global configuration we use command ASA>login, instead of en, kindly assist on how we can integrate this on script
ssh.
username:john.doe
Password:XXXXXX
ASA>
ASA>
ASA>login
username:localuser
password:Password212
Thank you in advance
Chris
Thanks for your feedback Chris.
We will consider this in one of our future (soon) posts.
Regards,
Admin team
Hi Chris,
You could use following commands instead of net_connect.enable()
time.sleep(1)
net_connect.send_command_expect(‘login’, expect_string=’username:’)
time.sleep(1)
net_connect.send_command_expect(‘localuser’, expect_string=’password:’)
time.sleep(1)
net_connect.send_command(‘Password212’)
This will send command and will read until it is detecting the given ‘expect_string’ back from the device
worked for me fine thanks for the script #sharingiscaring
but i need configuration backup of the device
Hi Sanket,
Hope you were able to successfully backup the configuration using the script.
Regards,
Admin team
but most of the devices it’s saying access failed backup did not taken may i know the reason why?
but most of the devices in our environment it’s failing it says access to device deviceaddress failed back up did not taken may i know the reason why?
please provide error
Please ensure you have reach ability to to device from the script running machine and you have given device ip address on iplist.txt file
and i want to know weather the script is using ssh or telnet to connect to devices?
This script using ssh to connect with device.
Hi,
Do you have any similar script for Dell Force10 switches?
Regards,
Ali
Hi Ali,
For now we have these scripts for Cisco devices only.
Regards,
Admin Team
Kindly suggest me how to make script using SSH and whole config backup save in Hostname not in IP address.
Please reply me very soon
Saving the output to a file with hostname of device instead of IP
——————————————————————-
You have to get the hostname of device using the command ‘sh run | in hostname’ first . This will give out put like ‘hostname MYROUTR’. Then you have to extract the router name from the output using regex feature available on python.
Following are the solution, modify the script as per below
add ‘import re’ to the beginning of script.
Then replace the line ‘filename=device[‘ip’]+’-‘+today+”.txt” ‘ with following commands
dev_name=net_connect.send_command(‘show run | in hostname’) // getting the hostname
hname=re.searc(r’hostname\s+(\w+)’,dev_name) //extracting the hostname from the putput
hostname=hname.group(1)
filename=hostname+today+”.txt” // generating file name
Complete modified script below
from netmiko import ConnectHandler
import getpass
import sys
import time
import re
##getting system date
day=time.strftime(‘%d’)
month=time.strftime(‘%m’)
year=time.strftime(‘%Y’)
today=day+”-“+month+”-“+year
##initialising device
device = {
‘device_type’: ‘cisco_ios’,
‘ip’: ‘192.168.43.10’,
‘username’: ‘username’,
‘password’: ‘password’,
‘secret’:’password’
}
##opening IP file
ipfile=open(“iplist.txt”)
print (“Script to take backup of devices, Please enter your credential”)
device[‘username’]=input(“User name “)
device[‘password’]=getpass.getpass()
print(“Enter enable password: “)
device[‘secret’]=getpass.getpass()
##taking backup
for line in ipfile:
try:
device[‘ip’]=line.strip(“\n”)
print(“\n\nConnecting Device “,line)
net_connect = ConnectHandler(**device)
net_connect.enable()
time.sleep(1)
print (“Reading the running config “)
output = net_connect.send_command(‘show run’)
time.sleep(3)
dev_name=net_connect.send_command(‘show run | in hostname’)
hname=re.searc(r’hostname\s+(\w+)’,dev_name)
hostname=hname.group(1)
filename=hostname+today+”.txt”
saveconfig=open(filename,’w+’)
print(“Writing Configuration to file”)
saveconfig.write(output)
saveconfig.close()
time.sleep(2)
net_connect.disconnect()
print (“Configuration saved to file”,filename)
except:
print (“Access to “+device[‘ip’]+” failed,backup did not taken”)
ipfile.close()
print (“\nAll device backup completed”)
If anyone is still visiting this blog feel free to copy my script to output the hostname as the filename. I was unable to get Naisamuddin PK’s script to work so if you are in the same situation, below is the solution.
Change the line that reads
filename=device[‘ip’]+’-‘+today+”.txt”
to
filename=net_connect.find_prompt()[:-1] +’-‘+today+”.txt”
can’t we run this script through pycharm?
As i tried, i unable to run.
Could you help please?
i unable to save the configuration with hostname and getting error messag, but with original script its working fine. Could you helpon this please
I have run the script example from admin, Naisamuddin PK and Juliet using Raspberry Pi 2 (Debian (version 2)).
I could SSH to my switch through prove that is working but running the script I kept getting the result below
pi@raspberrypi:~/Desktop/PyNet $ python3 ssh.py
Script to take backup of devices, Please enter your credential
User name:admin
Password:
Enter enable password:
Password:
Connecting Device 192.168.100.17
Access to 192.168.100.17 failed,backup did not taken
Connecting Device
Access to failed,backup did not taken
Connecting Device
Access to failed,backup did not taken
All device backup completed
this happen using the three example posted here
please can you advice what else to do. Is it best run on window only ?
I want to take backup of different vendor switches[cisco, HP, arista] on single script. How is it possible. On paramuko we can do but the problem is output not it in correct format (some ansi letters on that output). Is there any other solution?
Hello,
It works, thank you for sharing