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

2024-10-06 12:19:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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

有谁能给我指一个正确的方向,或者让我知道我做错了什么?

非常感谢!!


Tags: thepyreadtimelinealltelnetutf
1条回答
网友
1楼 · 发布于 2024-10-06 12:19:39

我通过在读取新行和回车后添加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()

相关问题 更多 >