簡體   English   中英

將輸出保存在多個文本文件中

[英]Save output in multiple text files

我有一個腳本,該腳本將連接到主機名列表,運行命令,然后將輸出打印到屏幕上。 我知道如何將輸出發送到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()

您可以執行以下操作:

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

而不是在workon函數上打印標准輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM