【发布时间】:2018-06-06 00:20:41
【问题描述】:
我在这里遇到了一个非常简单的错误。 我需要连接一些读取文件hosts.txt的设备并在文件.txt中打印输出,但我还需要在windows终端中读取。
这是脚本:
import sys
import telnetlib
user = "xxx"
password = "xxx"
file = open("hosts.txt", "r")
for line in file:
line = line.rstrip("\n")
tn = telnetlib.Telnet(line)
tn.read_until("Username: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("enable \n")
tn.write(password + "\n")
##
tn.write("dir\n")
tn.write("exit \n")
##
output = tn.read_until("exit")
print output
##
#sys.stdout=open(line + ".txt","w")
#print tn.read_all()
#sys.stdout.close()
在这里我可以在终端中看到,但是当我取消注释将输出写入文件的行(最后 3 行)时,我收到以下错误,停在第一个“主机”:
Traceback (most recent call last):
File "dir.py", line 26, in ?
print output
ValueError: I/O operation on closed file
[noctemp@svcactides check_ios]$
如何在屏幕和文件中同时打印输出?
Tks
【问题讨论】: