Is it possible to print the telnet response line by line, when a command executed over telnet keeps on responding over console ?
Example: I have executed a command (to collect logs), It keeps on displaying logs on console window. Can we read the response line by line & print it , without missing any single line ?
Below snippet writes the log, but only after certain specified time. If I stop the service/script (CTRL-C) in between, that doesn't write anything.
import sys
import telnetlib
import time
orig_stdout = sys.stdout
f = open('outpuy.txt', 'w')
sys.stdout = f
try:
tn = telnetlib.Telnet(IP)
tn.read_until(b"pattern1")
tn.write(username.encode('ascii') + b"\n")
tn.read_until(b"pattern2")
tn.write(command1.encode('ascii') + b"\n")
z = tn.read_until(b'abcd\b\n',600)
array = z.splitlines( )
except:
sys.exit("Telnet Failed to ", IP)
for i in array:
i=i.strip()
print(i)
sys.stdout = orig_stdout
f.close()
read_until
habors danger of leaving unread bytes in the telnet buffer. One tends to forget about those. E.g. in the above example we stop reading at "pattern1" and if there are still bytes after "pattern1" in the buffer we will first send the username and then read the bytes after "pattern1" up to "pattern2", so we rely on the fact that "pattern1" is really at the end of the buffer. It continues that everyread_until
may also read bytes left over from theread_until
before.This way one may loose track off the telnet response. – Everglades