【问题标题】:How to print/display the output of a telnet session and print out in the file as well - Python如何打印/显示 telnet 会话的输出并在文件中打印出来 - Python
【发布时间】: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

【问题讨论】:

    标签: python telnetlib


    【解决方案1】:

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

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

    改为使用print 打印到标准输出,然后打开一个单独的文件对象并写入该对象:

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

    【讨论】:

    • 我想我明白了,但现在它是一个语法错误:文件“dir.py”,第 33 行,open(line + ".txt","w") as f: ^ SyntaxError : 无效语法 [noctemp@svcactides check_ios]$
    • @Thiago:这似乎不对...您使用的是 Python 的古老版本吗?缩进不好?
    • 现在开始工作了!我刚刚调整了变量,它按我想要的方式工作!谢谢@Linuxios!
    • @thiago:太好了!很高兴我能帮上忙!如果答案解决了您的问题,最好在 StackOverflow 上标记绿色复选框,以便其他人知道问题已解决(“接受答案”)。祝你编程顺利!
    【解决方案2】:

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

    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)
    

    谢谢大家!

    【讨论】:

      猜你喜欢
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多