我有以下脚本允许我登录到不同的路由器并运行不同的命令,然后将它们输出到文件中,除了我为每个路由器获取一个文件之外,这很有效。所以我要做的就是看看我是否只能获得一个文件,无论我进入多少个盒子。我使用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()
答案 0 :(得分:1)
你有:
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()