如何 print/display telnet 会话的输出并在文件中打印出来 - Python

How to print/display the output of a telnet session and print out in the file as well - Python

我遇到了一个非常简单的错误。 我需要连接一些设备读取文件 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 行),我收到以下错误,在第一个 "host" 处停止:

Traceback (most recent call last):
  File "dir.py", line 26, in ?
    print output
ValueError: I/O operation on closed file
[noctemp@svcactides check_ios]$

如何同时在屏幕和文件中打印输出?

感谢

重新分配 sys.stdout 是个糟糕的主意。

第一次迭代后,您丢失了实际的 stdout 对象,然后关闭了替换它的文件,导致在下一次循环迭代中尝试写入时出现给定错误。

相反,使用 print 打印到标准输出,并打开一个 单独的 文件对象并写入:

output = tn.read_until("exit")
print output
##
with open(line + ".txt","w") as f:
  f.write(output)

问题解决了,最终脚本是这样的:

import sys
import telnetlib

user = "xx"
password = "xx"

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("sh run | i boot\n")
        tn.write("exit \n")

        output =  tn.read_until("exit")
        print output

        stdout=open(line + ".txt","w")
        stdout.write(output)

谢谢大家!