Category Archives: Uncategorized

Pay attention to ARP Poisoning in your network.

“The cruelest lies are often told in silence.”
— Robert Louis Stevenson

Cisco Router Backup Script With Python and Telnet

We needed a simple way to backup our network settings on a Cisco device at Veriteknik, so I decided to write a script.

You can simple connect to the device via telnet, declaring your username and password. For security reasons, we use IP address restricting as well.

So, it is quite easy to send and recieve telnet commands in Python, simply use the telnetlib library.

Getting the settings of a Cisco device is quite easy, simply enter the “sh run” command and the output is your settings. But normally the device will output the settings in bits and pieces, using a “more” like function. This is set on the terminal length parameter. To check it, simple use the following command on your device,

asr.vp.net.tr#show terminal | in Length
Length: 62 lines, Width: 195 columns

To set this value to 0, which means you’ll get the full output instantly,

terminal length 0

This command will change the option, but that is only for the current session. When you relog to the device, the value will be set to default, which is a good thing cause we want only our Python-Telnet session to get a non-more-like terminal mode. You can read about this on Cisco’s documentation here.

Now using the script below, we can simple get our backups. This script is for Python 2.x, it won’t be that different if you want to use it with 3.x either.

#!/usr/bin/python

import telnetlib
import datetime

now = datetime.datetime.now()

host = "192.168.1.2" # your router ip
username = "administrator" # the username
password = "SuperSecretPassword"
filename_prefix = "cisco-backup"

tn = telnetlib.Telnet(host)
tn.read_until("Username:")
tn.write(username+"\n")
tn.read_until("Password:")
tn.write(password+"\n")
tn.write("terminal length 0"+"\n")
tn.write("sh run"+"\n")
tn.write("exit"+"\n")
output=tn.read_all()

filename = "%s_%.2i-%.2i-%i_%.2i-%.2i-%.2i" % (filename_prefix,now.day,now.month,now.year,now.hour,now.minute,now.second)

fp=open(filename,"w")
fp.write(output)
fp.close()

This script will output a file with a timestamp. This file will contain all the settings (actually the “shell run” output) of your device. Now why not give it a try with a cronjob?