Script

import sys import time import paramiko import os import cmd import datetime #set date and time now = datetime.datetime.now() #authentication HOST = open('d:\python\hosts.txt') USER = 'user' PASSWORD = 'password' secret = 'password' all_ips = [ip.rstrip() for ip in HOST] #prefix files for backup filename_prefix ='cisco_backup'+ip print all_ips #ssh session starts client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(ip, username=USER, password=PASSWORD) #ssh shell chan = client.invoke_shell() time.sleep(1) #enter enable secret chan.send('en\n') chan.send(secret +'\n') time.sleep(1) #terminal lenght for no paging chan.send('term len 0\n') time.sleep(1) #show config and write output chan.send('sh run\n') time.sleep(10) output = chan.recv(99999) #show output config and write file with prefix, date and time print output filename = "%s_%.2i-%.2i-%i_%.2i-%.2i-%.2i" % (filename_prefix,now.day,now.month,now.year,now.hour,now.minute,now.second) f = open(filename, 'a') f.write(output) f.close() #close ssh session client.close() 

I write several ip-addresses to the hosts file, but at the output I receive only one file with the last address. The rest is not.

Where am I wrong? Logically, it seems that I open the file, read the addresses from it and run it further in the loop.

  • Where is the cycle? The only one that I see forms all_ips that are not printed anywhere except for printing ... - Vladimir Martyanov
  • That is, everything else in this cycle does not fall? - mikonoid
  • No, what you can easily make sure of putting at the beginning of the "rest" print "start" - Vladimir Martyanov
  • I do not really understand how to cram it into a cycle. I also try it like this: f = open ('hosts.txt') for ip in f.readlines (): But the same goes ... - mikonoid
  • one
    Start by printing each line of the file, then gradually add the rest of the code to the loop body. - Vladimir Martyanov

1 answer 1

I can assume you are mistakenly interpreting the code [ip.rstrip() for ip in HOST] . It does not initiate a cycle. This is the so-called list generator . All he does is write a new list to the variable all_ips , formed by applying str.rstrip() to each line in the HOSTS file.

Generator expressions are, without a doubt, an extremely powerful language tool. But in this case, it would be logical to use a normal loop :

 for ip in hosts: filename_prefix = 'cisco_backup' + ip # И прочие ваши действия с элементом списка 

I will not be polite and not original, but please read the docks .

  • one
    By the way, in Python 3, local names in list comprehension such as ip cannot escape from context. OP would get NameError . - jfs