How to print telnet response line by line?

Is it possible to print the telnet response line by line when a command executed through telnet continues to respond to the console?

Example: I ran a command (to collect logs), it continues to display logs in the console window. Can we read the answer line by line and print it without missing a single line?

A log is written below the fragment, but only after a certain time. If I stop the / script service (CTRL-C) between them, it does not 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()
+4
source share
2 answers

You can use it tn.read_until("\n")in a loop to read the single line execution of your telnet command

while True:
    line = tn.read_until("\n")  # Read one line
    print(line)
    if 'abcd' in line:  # last line, no more read
        break
+2
source

ready_very_eager, read_eager, read_lazy ready_very_lazy, , . "" .

0

Source: https://habr.com/ru/post/1569540/


All Articles