Thursday, 14 September 2017

Python for network engineer :- Cisco router config backup using Python2.7



Below script is used to take backup of multiple devices. Make sure when you call a file in python then that file must be stored in same folder where you are storing your python script.

e.g both ip.txt must in same folder where you are storing you python program.

Note:- Make sure router IP must be reachable from the machine where python script is configured.



File used in the scripts are :-

ip.txt :- A notepad file contains below router IP address.

192.168.10.1
192.168.10.2
192.168.10.3


import telnetlib
import datetime

now = datetime.datetime.now()
ips = [i.strip() for i in open("ip.txt")]
username = "test"
password = "test"

for ip in ips:
    filename_prefix = (ip)
    tn = telnetlib.Telnet(ip)
    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()

No comments:

Post a Comment