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, 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.


import telnetlib
import datetime

now =

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

tn = telnetlib.Telnet(host)
tn.write("terminal length 0"+"\n")
tn.write("sh run"+"\n")

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


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?