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

时间:2018-05-31 17:31:32

标签: python telnetlib

我在这里面临一个非常简单的错误。 我需要连接一些设备读取文件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]$

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

韩国社交协会

2 个答案:

答案 0 :(得分:0)

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

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

相反,使用print打印到stdout,然后打开一个单独的文件对象并写入:

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

答案 1 :(得分:0)

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

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)

谢谢大家!