[英]writing a single file per loop vs many in python
我有以下腳本,該腳本允許我登錄不同的路由器並運行不同的命令,然后將它們輸出到一個文件中,這很好用,只是我進入的每個路由器都有一個文件。 因此,我要做的就是看看無論裝入多少盒,我都只能得到一個文件。 我使用host.txt文件定義路由器,並使用commands.txt文件定義要運行的命令。
import telnetlib
user = "user"
password = "password"
#Getting list of Sites to use and logging in
with open('host.txt', 'r') as hostlist:
host = [line.strip() for line in hostlist]
for hostname in host:
tn = telnetlib.Telnet(hostname,23,30)
print "Grabbing data from site"
tn.read_until("Username: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("\n")
tn.write("term length 0\n")
with open('commands.txt', 'r') as commandlist:
commands = [line.strip() for line in commandlist]
for commandcall in commands:
tn.write(commandcall + "\n")
tn.write("exit\n")
outFile = open(hostname + ".txt", "wt")
outFile.write (tn.read_all())
outFile.close()
tn.close()
你有:
host = [line.strip() for line in hostlist]
for hostname in host:
然后:
outFile = open(hostname + ".txt", "wt")
outFile.write (tn.read_all())
outFile.close()
因此,每個主機名都將生成一個新文件是有意義的,因為您將遍歷循環時將outFile.open()的參數更改為每個主機名。
如果將open()的參數設置為靜態字符串,則應該執行所需的操作。 您還希望使用“ a”附加。
outFile = open("RouterLog.txt", "a")
outFile.write (tn.read_all())
outFile.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.