If you are a network or systems engineer, then you would know the complexity of taking network configuration backups of a large number of network devices in your organization or company. Let’s assume suddenly one day you will see one of your routers/switches die without any errors. And guess what, you have not logged in to that device from the initial setup and you do not get a chance often to look into it and are not aware of many of the configurations inside it. Now, you got stuck in this situation and wondered what to put in configurations. So without having any configuration backups, you are left with no options.
Alright, so now we know that we have a problem but how to fix it? As a solution, there are many network monitoring tools and configuration backup tools available on the web which is available to do all these tasks but they may cost. But what if you can come up with your own solution using a few amounts of script lines? That will save money and you have a fully customized solution.
In this post, I’m going to help you to develop a full-fledged network configuration backup tool to automate Cisco devices configuration backup (Routers, Switches, Wireless Controllers, and Firewalls) with python script by using the Netmiko Python module.
Python for Network Automation
Python is one of the most popular languages for network automation, but only having python can not do automation tasks easily. Fortunately, someone did a great job by creating libraries or modules that manage a lot of the details of network automation using Python. So if you start with automation should first gain a basic understanding of Python scripting.
Network Automation Libraries/Modules
Python network automation libraries give you simplified communication and management with a large number of network devices. There are several Python libraries/modules are available to do the network automation tasks such as Paramiko, Netmiko, and NAPALM. But in this article, I’m using the Netmiko Python library for network automation tasks.
About Netmiko Module
The Netmiko library is an enhanced version of the Paramiko library. It is a multi-vendor library that simplifies SSH connection to a network device and does a particular operation like command execution on the device.
You can find the library at https://github.com/ktbyers/netmiko and the latest released version of the software can be downloaded here.
The main objectives of this library are:
- Easily establish an SSH connection to a large number of devices using a single script.
- Command execution and get the output simply to the text file or terminal.
- Simplify command execution of configuration commands including possibly commit actions.
- Supports a large number of multi-vendor network devices and platforms.
Before starting, you need to arrange the following things
- All the network devices should have SSH enabled, you can also do this with telnet but here I’m using SSH.
- Check the SSH connectivity from the Linux host to all network devices.
- Create separate text files including device IP addresses for each category of network devices (Routers, Switches, Wireless Controllers, and Firewalls) that you need to be backed up.
- Create a location to store all network device backups. (In here I’m using /root/Network_Device_Backups/<device_type>/<device_hostname>)
- Set up a TFTP server to push configurations of some network devices (will show how to set up it in this post).
In this article, I’m using Ubuntu/Debian distribution as OS and Python 3 as my scripting language.
Install & Configure Python Environment
Install Python 3.
apt update
apt upgrade
apt install python3 python3-pip
Install & verify netmiko python module.
pip3 install "pip>=20"
pip3 install netmiko
#Verify the installed module
pip list | grep netmiko
Create network device configuration backup locations.
mkdir -p /root/Network_Device_Backups/Router
mkdir -p /root/Network_Device_Backups/Switch
mkdir -p /root/Network_Device_Backups/WLC
mkdir -p /root/Network_Device_Backups/ASA
Task of Configuration Backup Script
This python script uses a list of device IP addresses from a JSON file. Once the script imports the JSON file, it extracts the list of IP addresses and uses a for loop to connect to each device and copies the contents of a running-configuration command “show running-config
“, VLAN output command “show vlan
” and writes the contents to a file on the server running the script. Finally, the script appends a date time stamp to the file and puts it in a separate directory for each device on the server the script is running on.
You can create a directory anywhere and keep these 2 files together in the same directory. In my case, I’m keeping this 2 files inside /root/Backup_Scripts
.
Device List as JSON File
#router.json
{
"router_list": [
{
"hostname": "RTR_A",
"ip": "192.168.1.100"
},
{
"hostname": "RTR_B",
"ip": "192.168.2.100"
}
]
}
#switch.json
{
"switch_list": [
{
"hostname": "SW-A",
"ip": "172.16.0.1"
},
{
"hostname": "SW-B",
"ip": "172.16.0.2"
}
]
}
Router/Switch Configuration Backup Script
The below script is for the Cisco routers, but this will also work for Cisco switches as well. Please make sure to change “router” keyword with “switch” accordingly.
#!/usr/bin/python3
from netmiko import ConnectHandler
import os
import time
import datetime
import json
device_list = '/root/Backup_Scripts/router.json'
backup_filename = 'RTR-Config-Backup-' + '{0:%Y-%m-%d-%H-%M-%S}'.format(datetime.datetime.now()) + '.cfg'
vlan_filename = 'RTR-Show-VLAN-' + '{0:%Y-%m-%d-%H-%M-%S}'.format(datetime.datetime.now()) + '.txt'
with open(device_list) as json_file:
data = json.load(json_file)
# Change data['router_list'] to data['switch_list'] if you are using switch.json
for router in data['router_list']:
cisco_2960 = {
'device_type': 'cisco_ios',
'host': router['ip'],
'username': 'sshusername', # Provide SSH username
'password': 'sshpassword', # Provide SSH password
'secret': 'enablesecret', # Optional, defaults to ''
}
try:
net_connect = ConnectHandler(**cisco_2960)
except:
continue
net_connect.enable()
output_run_config = net_connect.send_command("show running-config")
output_vlan = net_connect.send_command("show vlan-switch")
net_connect.exit_enable_mode()
net_connect.disconnect()
#Create a separate directory for each device if not exists.
backup_dir = '/root/Network_Device_Backups/Router/'+router['hostname']
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
#Write the device running-config to a file.
f0 = open(backup_dir+'/'+backup_filename, 'w')
f0.write(output_run_config)
f0.close()
#Write the device VLAN output to a file.
f1 = open(backup_dir+'/'+vlan_filename, 'w')
f1.write(output_vlan)
f1.close()
Setup TFTP Server for WLC Configuration Backup
Install the TFTP
apt update
apt install xinetd tftpd tftp
Configure the TFTP
Create a file /etc/xinetd.d/tftp
and put the following block inside it.
service tftp
{
protocol = udp
port = 69
socket_type = dgram
wait = yes
user = nobody
server = /usr/sbin/in.tftpd
server_args = /tftpboot
disable = no
}
Create the TFTP Location
Create a folder “tftpboot” inside the root location and this should match whatever you gave in server_args
. Mostly it will be tftpboot location where your network device configuration backups are stored. Also, grant required permissions to access the tftpboot.
sudo mkdir /tftpboot
sudo chmod -R 777 /tftpboot
sudo chown -R nobody /tftpboot
Restart the xinetd Service
/etc/init.d/xinetd stop
/etc/init.d/xinetd start
Wireless Controller Configuration Backup Script
Once you are done with the above TFTP server setup you can proceed with the following script to backup your Cisco wireless controller. Simply what this script does is command the wireless controller to upload the configuration backup to the TFTP server and once it is uploaded, copy the configuration file to the given backup location (/root/Network_Device_Backups/WLC).
#!/bin/python3
from netmiko import ConnectHandler
import time
import datetime
import os
import shutil
tftp_server = '192.168.100.100'
tftp_location = '/tftpboot'
backup_filename = 'WLC-Config-Backup-' + '{0:%Y-%m-%d-%H-%M-%S}'.format(datetime.datetime.now()) + '.cfg'
backup_location = '/root/Network_Device_Backups/WLC/'
net_connect = ConnectHandler(device_type='cisco_wlc', host='172.16.0.1', username='sshusername', password='sshpassword')
net_connect.find_prompt()
config_commands = ['transfer upload mode tftp',
'transfer upload datatype config',
'transfer upload filename '+backup_filename,
'transfer upload path .',
'transfer upload serverip '+tftp_server,
]
# Sending backup configuration settings to device
net_connect.send_config_set(config_commands)
# Initiating transfer
output1 = net_connect.send_command_timing('transfer upload start')
# Confirming start of transfer
output2 = net_connect.send_command_timing('y')
#time.sleep(5)
# Disconnect from device
net_connect.disconnect()
file_path = tftp_location+backup_filename
while not os.path.exists(file_path):
time.sleep(65)
if os.path.isfile(file_path):
shutil.move(file_path, backup_location)
Setup FTP Server for ASA Configuration Backup
Install the vsftpd
apt update
apt install vsftpd
vsftpd service will automatically start after the installation process is complete. Verify it by executing the service status:
systemctl status vsftpd
Configure the vsftpd
The vsftpd server can be configured by modifying the vsftpd.conf
file, found in the /etc
directory.
# Allow anonymous FTP? (Disabled by default).
anonymous_enable=NO
# Allow local users to log in.
local_enable=YES
# Enable any form of FTP write command.
write_enable=YES
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
local_umask=022
# Restrict local users to their home directories.
chroot_local_user=YES
allow_writeable_chroot=YES
Save the file and restart the vsftpd service for changes to take effect:
systemctl restart vsftpd
**If you are running a UFW firewall you’ll need to allow FTP traffic.
Create FTP User
adduser asaftpuser
Cisco ASA Firewall Configuration Backup Script
Here also the same as the previous one, you have to give the TFTP server details to send the backups to /tftpboot
. Then once the backup is available in /tftpboot
, move it to the required backup location.
#!/usr/bin/python3
from netmiko import ConnectHandler
import sys
import os
import time
import datetime
import shutil
ftp_server = '192.168.100.100'
ftp_location = '/home/asaftpuser/'
backup_filename = 'FW-Config-Backup-' + '{0:%Y-%m-%d-%H-%M-%S}'.format(datetime.datetime.now()) + '.tar.gz'
backup_location = '/root/Network_Device_Backups/ASA/'
cisco_asa = {
'device_type': 'cisco_asa',
'host': '192.168.1.1',
'username': 'sshusername',
'password': 'sshpassword',
'secret': 'enablesecret',
}
try:
net_connect = ConnectHandler(**cisco_asa)
except:
print >> sys.stderr, "Unable to connec to ASA."
sys.exit(1)
net_connect.enable()
backup_command = "backup location ftp:"
result = net_connect.send_command_timing(backup_command)
ftp_url = 'ftp://asaftpuser:[email protected]/'+backup_filename
if 'Press return to continue or enter a backup location' in result:
result += net_connect.send_command_timing(ftp_url)
net_connect.exit_enable_mode()
net_connect.disconnect()
file_path = ftp_location+backup_filename
while not os.path.exists(file_path):
time.sleep(10)
if os.path.isfile(file_path):
shutil.move(file_path, backup_location)
Let’s Start the Testing
Now, we should be able to run this Python device configuration backup script, but need to make this script executable with the following command.
cd /root/Backup_Scripts
chmod u+x *
Run the scripts manually with the following commands.
python3 Router_Backup_Script.py
python3 Switch_Backup_Script.py
python3 WLC_Backup_Script.py
python3 ASA_Backup_Script.py
Verify the location given in the code (/root/Network_Device_Backups in my case ) for the backup file.
Schedule to Run the Script
Finally, It is time to add a cronjob to run this script schedule at a particular time of the day. All you need to do is to copy your script in the Daily/Weekly/Monthly folder at the following directory. Or else add it as following way which runs this script weekly at 01:00 AM.
crontab -e
30 1 * * 5 /usr/bin/python3 /root/Backup_Scripts/Router_Backup_Script.py
20 1 * * 5 /usr/bin/python3 /root/Backup_Scripts/Switch_Backup_Script.py
10 1 * * 5 /usr/bin/python3 /root/Backup_Scripts/WLC_Backup_Script.py
0 1 * * 5 /usr/bin/python3 /root/Backup_Scripts/ASA_Backup_Script.py
Conclusion
That’s all about automating the network device configuration backup of Cisco devices with Python script using netmiko python module on a Linux server running Debian/Ubuntu. Hopefully, you can find more details about the Netmiko Python module here. If you have any questions or suggestions you can always leave your comments below. I will try my best to review and reply to them.
1 comment
Please may I have the video on how to implement the scripts?