将输出保存在多个文本文件中

时间:2015-12-22 18:57:03

标签: python cisco

我有一个脚本,它将连接到主机名列表,运行命令,并将输出打印到屏幕。我知道如何将输出发送到txt文件,但我想以每个主机上的输出将创建自己的txt文件的方式进行设置。理想情况下,我希望将文件保存为host1.txt,host2.txt等。如果有更简单/更智能的方法,请打开其他想法。

import sys, os, string, threading
import getpass
import paramiko


cmd = "sh vl bri"
lanid = raw_input("Enter your uname: ")

#get password info
def enterPassword():
  while True: # repeat forever
    pwd = getpass.getpass('Enter password:')
    password_again = getpass.getpass('Confirm password:')
    if pwd != password_again:
      print 'Password and confirmation do not match.Please try again!!'
    else:
      return pwd
pwd = enterPassword()

outlock = threading.Lock()

def workon(host):

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username=lanid, password=pwd)
    stdin, stdout, stderr = ssh.exec_command(cmd)
    print stdout.read()
    stdin.flush()

    with outlock:
        print stdout.readlines()

def main():
    hosts = ['host1', 'host2', 'host3', ] # etc
    threads = []
    for h in hosts:
        t = threading.Thread(target=workon, args=(h,))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()

main()

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

with open("output-" + host, 'w') as f:
    f.write(stdout)

而不是在 workon 函数

上打印stdout