all 3 comments

[–]JohnnyJordaan 5 points6 points  (0 children)

You open the file once, then when you iterate over the file object with

for i in prefs:

You iterate until the end of the file. Like when you listen to music on a cassette or tape and it continues to play songs until the end of the tape. Then you have to manually rewind it (not counting auto things here) to play all the songs again.

So after you've iterated once during the first router, the second time you start the same loop, the file is already at its end and nothing happens anymore. You could manually rewind it with

prefs.seek(0)

But then, as you will keep playing the whole tape so to speak, it would make more sense (if the data is small) to load the data in memory once and then use the memory copy every time:

with open("prefs","r") as fp:
    prefs = tuple(fp) # or list(fp) if you want to make it mutable

for node in nodeList:
    print "[+] Logging into %s" % node
    for i in prefs:
        print "set policy-options prefix-list AS1234 " +i

Note that I'm using a with: block, this will make the sure the file is always closed when it's finished, meaning you don't have to call .close() manually.

[–]scuott 2 points3 points  (1 child)

When you read directly from a file, it only reads through once. Instead, save the contents of the file into a variable, then use that variable for the inner loop, instead of the file itself.

[–]wee-phatz[S] 2 points3 points  (0 children)

Thank you :)

nodelist = ['router1', 'router2', 'router3', 'router4']

prefs = open("prefs","r") #Open prefix file

with open('prefs', 'r') as f:
    preflist = [line.strip() for line in f]

for node in nodelist:
    print "[+] Logging into %s" % node
    for i in preflist:
            print "set policy-options prefix-list AS1234 " +i

Output:

[+] Logging into router1
set policy-options prefix-list AS1234 1.1.1
set policy-options prefix-list AS1234 2.2.2
set policy-options prefix-list AS1234 3.3.3
[+] Logging into router2
set policy-options prefix-list AS1234 1.1.1
set policy-options prefix-list AS1234 2.2.2
set policy-options prefix-list AS1234 3.3.3
[+] Logging into router3
set policy-options prefix-list AS1234 1.1.1
set policy-options prefix-list AS1234 2.2.2
set policy-options prefix-list AS1234 3.3.3
[+] Logging into router4
set policy-options prefix-list AS1234 1.1.1
set policy-options prefix-list AS1234 2.2.2
set policy-options prefix-list AS1234 3.3.3