如何从Python中的telnet查询中读取多行?

时间:2015-01-27 12:46:35

标签: python telnet python-3.4 telnetlib

我正在尝试使用Python的telnetlib模块与设备通信。我似乎能够建立连接并将我的查询传递给设备,但输出并不是我所期望的。

这是我的简化代码:

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

执行此代码后,所有终端显示为:mpa:? - 不是我期待的处理器信息。

当我使用Telnet客户端时,在建立连接后,我得到一个 mpa:?提示符,表示设备已准备好接受我的命令。然后我输入'v',它应该以这种格式产生输出:

mpa:? v

FIRMWARE CONFIGURATION:
Processor Firmware Type
Build Number
Copyright Info

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

mpa:?

查询完成后,会显示 mpa:?提示符,为下一个命令做好准备。

我代替print(tn.read_eager().decode('utf-8'))尝试了print(tn.read_all().decode('utf-8')),但这次超时时出现以下错误消息:

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

有人能指出我正确的方向,还是让我知道我做错了什么?

非常感谢!!

1 个答案:

答案 0 :(得分:2)

我已经通过添加while循环来解决问题,在读取新行和回车符后打印每一行:

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()