Search code examples
pythontelnetlib

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


I'm facing a pretty simple error here. I need to connect in some devices reading a file hosts.txt and print out the output in the files .txt, but I also need to read in the windows terminal.

Here is the script:

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()

Here I can see in the terminal but when I uncomment the lines to write the output on files (last 3 lines), I get the following error, stoping in the first "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]$

How can I print the output in the screen AND in the file at the same time?

Tks


Solution

  • Reassigning sys.stdout is a terrible idea.

    After the first iteration, you've lost the actual stdout object and then close the file you've replaced it with, resulting in the given error when you try to write to it in the next iteration of the loop.

    Instead, use print to print to stdout, and open a separate file object and write to that:

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