First useful tip

Wed 18 December 2019

So I recently took a python networking and web-api class, and I had the opportunity to learn a couple of new and really useful tips. I plan on illustrating one of those in this post today.

ips = ["10.10.10.1", "10.10.10.2", "10.10.10.3", "10.10.10.4", "10.10.10.5", "10.10.10.6", "10.10.10.7", "10.10.10.8", "10.10.10.9"]


for n in ips:
    pre_con = paramiko.SSHClient()
    pre_con.set_missing_host_key_policy(parmiko.AutoAddPolicy())
    pre_con.connect(n, username="cisco", password="cisco")
    conn = pre_con.invoke_shell()
    conn.send("\nterm leng 0 \n")
    conn.send("enable\ncisco\n")
    conn.send("show ip route")
    conn.recv(65535)

That script example was a simple paramiko connection script taht loops through a list designated with "ips" variable. but I wanted to autopopulate the IPS variable with IPs that had the last digit sequentially increased. So I came up with a one line command that works in the python shell quite well.

ips = ["10.10.10.{}".format(i) for i in range(1,9)]

In this fashion, I don't have to type out the repetitive ip addresses when they are simply sequential. If you are dealing with a ton of different IPs and they are not sequential at all, the other best option is to put them in a flat text file and read the file in just looping through each line.

file = glob.glob("*ipaddress*")

FH = open(file[0], "r")

for line in FH.readlines():
    ips = []
    ips += line

Both are very effective ways of quickly putting together a list of IPs to loop through to perform a function

blogroll

social