2

I need to establish a connection to a telnet server which continually broadcasts information and save all of that information to a file. For testing, I am using the famous ASCII Star Wars located on towel.blinkenlights.nl

In essence, I need to replicate in Python what you get when inputting the following command into Windows Command Prompt: telnet towel.blinkenlights.nl /f c:/randfolder/output.txt

The below does establish the connection and is showing the data received in terminal, however I am having no luck in saving what I see in the terminal to a file:

import telnetlib

HOST = "towel.blinkenlights.nl"
PORT = "23"

telnetObj=telnetlib.Telnet(HOST,PORT)
outF = open("output.txt", "a")
outF.write(telnetObj.interact())

telnetObj.close()

1 Answers1

2

While this seems to me to be a rather hacky solution, using stdout does output the telnet stream to a file as required. Running this creates and appends a file containg all of the data received until interrupted

import sys
import telnetlib

with open('output.txt', 'w') as output:
    sys.stdout = output # this is where the magic happens
    HOST = "towel.blinkenlights.nl"
    PORT = "23"

    telnetObj=telnetlib.Telnet(HOST,PORT)
    outF = open("output.txt", "a")
    outF.write(telnetObj.interact())

    telnetObj.close()

Would not be surprised however, if incorrect handling of this approach caused mess in program that this is part of. I'm thinking running it as a separate process could be reasonably safe.