Python 将输出保存在多个文本文件中
我有一个脚本,它将连接到主机名列表,运行命令,并将输出打印到屏幕上。我知道如何将输出发送到txt文件,但我希望将其设置为每个主机上的输出将创建自己的txt文件。理想情况下,我希望将文件另存为host1.txt、host2.txt等。如果有更简单/更智能的方法来实现这一点,可以向其他人开放Python 将输出保存在多个文本文件中,python,cisco,Python,Cisco,我有一个脚本,它将连接到主机名列表,运行命令,并将输出打印到屏幕上。我知道如何将输出发送到txt文件,但我希望将其设置为每个主机上的输出将创建自己的txt文件。理想情况下,我希望将文件另存为host1.txt、host2.txt等。如果有更简单/更智能的方法来实现这一点,可以向其他人开放 import sys, os, string, threading import getpass import paramiko cmd = "sh vl bri" lanid = raw_input("E
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函数上打印标准输出,而是尝试了一下,但我发现缩进错误。仍然是新的脚本,所以我确信这是一个简单的定义工作(主机):ssh=paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(主机,username=lanid,password=pwd)stdin,stdout,stderr=ssh.exec_命令(cmd)#打印stdout.read(),打开(“输出-”+host,'w')作为f:f.write(stdout)stdin.flush()和outlock:print stdout.readlines()为前面注释的格式表示歉意。仍在试图找出如何将代码粘贴到注释中。