Tuesday, March 26, 2013

Telnet Automation using Python: Copy CISCO configs to TFTP server

Enterprise is using TELNET for CISCO management. It wants to design an automated script that will copy config (either startup-config or running-config) of the CISCO routers and switches to the TFTP server. TFTP server has separate folder for each routers.
There are the times when a network engineer forgets to copy router config to the TFTP server after he/she makes changes to CISCO config. This little python script can be scheduled to copy configs periodically saving network engineers from possible unforeseen havoc because they don't have backup copy of the router config and router has crashed.

Note: This Python script is based on  Python version 3.3. You can execute this script on both windows and linux/unix environment. You can download python from http://www.python.org/getit/. When you install python make sure that python is added to your system environment variables.

#File name: telnetautomation.py
#Script starts here
import getpass
import sys
import telnetlib
import time

pwd1 = "user_exec_mode_password"
pwd2 = "privilege_exec_mode_password"
config = "startup-config"

#Create a list of router IP address, folder location and router hostname  

hostlist= [ ("router1_ip_address","plano","planoRouter1"),

#Use for loop to telnet into each routers and execute commands
for host in hostlist:
    cmd1 = "en"
    cmd2 = "copy "+config+" tftp://tftp_server/cisco/"+host[1]+"/"+host[2]+".txt"
#copy startup-config  tftp://tftp_server/plano/planoRouter1.txt

    tn = telnetlib.Telnet(host[0])

    tn.write(pwd1.encode('ascii') + b"\n")
    tn.write(cmd1.encode('ascii') + b"\n")
    tn.write(pwd2.encode('ascii') + b"\n")
    tn.write(cmd2.encode('ascii') + b"\n")

sys.exit("operation completed")

#script ends here

[Note: TELNET is not my favorite protocol as it is very insecure. Communication is done in plain text. However, there are many enterprises still running this insecure protocol in their environment. Upgrade to SSH and disable TELNET in your environment if possible.]

No comments: