Thursday 14 September 2017

Python for network engineer :- Configure multiple router using telnet :-python 2.7


Below script is used to configure multiple devices. In below script ACL needs to be applied to multiple routers. Both Router IP and configuration are stored in different files 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 config.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 :-

Config.txt :- A notepad file contains below ACL configuration

conf t

ip access-list extended Restrict_Outlets
Permit ip any 10.130.127.0 0.0.0.255
deny ip any 10.126.0.0 0.1.255.255
deny ip any 10.128.0.0 0.3.255.255
deny ip any 10.175.0.0 0.0.255.255
deny ip any 10.176.0.0 0.7.255.255
deny ip any 10.190.0.0 0.1.255.255
deny ip any 10.192.0.0 0.15.255.255
deny ip any 10.208.0.0 0.1.255.255
deny ip any 10.210.0.0 0.0.255.255
deny ip any 10.60.0.0 0.0.255.255
permit ip any any

int fa3/0
ip access-group Restrict_Outlets out
no shut

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

192.168.10.1
192.168.10.2
192.168.10.3
====================Program============

import time
import telnetlib
import sys

#=====Credential for the devices
user = "test"
password = "test"

#=====config.txt contains the ACL

g = open('config.txt', 'r+')   
str = g.read()
g.close

#=====Extracting routers IP from ip.txt file and storing it in variable ips.

ips = [i.strip() for i in open("ip.txt")]

#=====Below FOR loop is  configuring ACL to one router at a time.

for ip in ips:
     telnet = telnetlib.Telnet(ip)
     telnet.read_until("Username: ")
     telnet.write(user + "\n")
     telnet.read_until("Password: ")
     telnet.write(password + "\n")
     telnet.write(str)
     telnet.write("end\n")
     telnet.write("exit\n")
     time.sleep(5)
     print ip
     print telnet.read_all()

====================END============

Router config example:-

hostname R1

interface FastEthernet0/0
 ip address 192.168.10.1 255.255.255.0
 duplex full
 no shut

interface FastEthernet3/0
 no ip address
 ip access-group Restrict_Outlets out ----<<<<<
 shutdown
 duplex auto
 speed auto

line vty 0 4
 login local
line vty 5 16
 login local
!
!
end






No comments:

Post a Comment