How to print telnet response line by line?
Asked Answered
W

2

7

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()
Wellmeaning answered 31/12, 2014 at 11:58 Comment(2)
you are directing the output to f so how do you think you can print it to the screen?Bwana
Working with telnet currently i made the observation that using 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 every read_until may also read bytes left over from theread_untilbefore.This way one may loose track off the telnet response.Everglades
B
6

You can use tn.read_until("\n") in a loop in order to read one line durint execution of your telnet command

while True:
    line = tn.read_until(b"\n")  # Read one line
    print(line)
    if b'abcd' in line:  # last line, no more read
        break
Bordie answered 31/12, 2014 at 12:6 Comment(1)
Thank You Secator. That's exactly what i wanted.Wellmeaning
N
2

You can use the ready_very_eager, read_eager, read_lazy, and ready_very_lazy functions specified in the documentation to read your stream byte-by-byte. You can then handle the "until" logic on your own code and at the same time write the read lines to the console.

News answered 31/12, 2014 at 12:5 Comment(2)
read_very_eager & read_eager both prints telnet response along with ' ' , which is not needed. Both prints ' ' , if no cooked data available. read_lazy & read_very_lazy both prints only ' ' .Wellmeaning
I think this answer is underrated as read_until is suitable only, if you know what to expect. Also it has the danger of leaving unread data in the telnet queue which is read interferingly in the next round.Everglades

© 2022 - 2024 — McMap. All rights reserved.