This is my first but not last post on using some programming language to automate the way how I interact with a Cisco or non-Cisco network device. Imagine having hundreds or thousands devices making even a simple configuration change or gathering some piece of information, that’s quite a lot of time.
Sometimes you might also need to do a task either on a single production device or on testing one but doing it would take a lot of time, imagine adding 500.000 IP Routes on one of your Lab Router!. Well probably you won’t see such an example anywhere (except when you have a traffic generator, and you do some kind of performance testing), but nowadays using BGP you simply get this amount of IP Routes from a couple of BGP Neighbors, so very rarely a single one would generate such amount of prefixes.
Back to our topic, since Python is becoming so popular nowadays and because I was trying to automate the way I create Static IP Routes on a Cisco router I decided to offload this part to a simple Python script. With around 15 lines of code I saved myself probably weeks or even months of my time if I would do the same manually by CLI. For example, if I would like to have some static routes similar as below:
ip route 10.1.1.1 255.255.255.255 Null0
ip route 10.1.1.2 255.255.255.255 Null0
ip route 10.1.1.3 255.255.255.255 Null0
…
Now let’s imagine I want to have something like this, the range of static (host) routes I need is from 10.1.1.1 – 10.10.255.255, summing up this we come up with around 647.700 static (host) routes, which corresponds exactly to the current Global IPv4 Routing Table capacity.
The script below will generate this amount of static routes, and write the same to an external file called “write.txt”, all of this within seconds and not weeks or months as we would manually do.
#Creates a new text file “write.txt”
text_file = open(“write.txt”, “w”)#Second octet starts with “1”
second_octet = 1#If second octet is equal or less than 10 continue with the next Loop
while second_octet <= 10:
second = str(second_octet)
third_octet = 1#If the third octet is equal or less than 255 than continue with the next loop
while third_octet <= 255:
third = str(third_octet)
last_octet = 1#If the last octet is equal or less than 254 than write the current IP Address to File
while last_octet <= 254:
last = str(last_octet)
text_file.write(“ip route 10.”+second+”.”+third+”.”+last+” 255.255.255.255 Null0\n”)
last_octet += 1
third_octet += 1
second_octet += 1
#At the end when the loops finish based on the conditions close the File.
text_file.close()
I remember my first programming lessons in University, it was Java, but honestly it was not as interesting as it is now for me, especially Python which is more user friendly I believe.
You can also download the script file attached Static_IP_Route.
Categories: Python
Hi, how i run this script??
Kevin, you can run it from anywhere, though if you copy-paste you might need to format it a little bit.