How can I read multiple lines from a telnet query in Python?

skyhammer picture skyhammer · Jan 27, 2015 · Viewed 7.2k times · Source

I am attempting to communicate with a device using Python's telnetlib module. I seem to be able to establish a connection and pass my query to the device, however, the output is not what I expect.

Here is my simplified code:

import telnetlib
import time

HOST = "10.10.10.71"

tn = telnetlib.Telnet(HOST, port=55555, timeout=60)

time.sleep(5)                # Give the processor time to connect

tn.write(b'v' + b'\r\n')     # Get the processor version, using 'v'

print(tn.read_eager().decode('utf-8'))

tn.close()                   # Close the connection

After executing this code, all the terminal displays is: mpa:? -- not the processor information I was expecting.

When I use a Telnet client, after establishing the connection, I get an mpa:? prompt, which indicated the device is ready for my command. I then type in 'v', which should produce an output in this format:

mpa:? v

FIRMWARE CONFIGURATION:
Processor Firmware Type
Build Number
Copyright Info

HARDWARE CONFIGURATION:
Line 1          - xxxx
Line 2          - xxxx
Line 3          - xxxx
...

mpa:?

After the query, the mpa:? prompt is displayed, ready for the next command.

In place of print(tn.read_eager().decode('utf-8')), I have also tried print(tn.read_all().decode('utf-8')), but this times out with the following error message:

Traceback (most recent call last):
File "C:/Python/Telnet_logger_1.py", line 14, in <module>
print(tn.read_all().decode('utf-8'))
File "C:\Python34\lib\telnetlib.py", line 335, in read_all
self.fill_rawq()
File "C:\Python34\lib\telnetlib.py", line 526, in fill_rawq
buf = self.sock.recv(50)
socket.timeout: timed out

Would anyone be able to point me into the right direction, or let me know what I'm doing wrong?

Many thanks!!

Answer

skyhammer picture skyhammer · Jan 27, 2015

I have resolved the problem by adding a while-loop to print each line after a new line and carriage return has been read in:

import telnetlib

HOST = "10.10.10.71"

tn = telnetlib.Telnet(HOST, port=55555, timeout=60)

tn.read_until(b"mpa:?")

tn.write(b'v' + b'\n\r')

while True:
    line = tn.read_until(b"\n\r")  # Check for new line and CR
    print(line)
    if (b"mpa:?") in line:   # If last read line is the prompt, end loop
        break

tn.close()