gpt4 book ai didi

Python telnetlib read_until 返回截断的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 00:48:20 27 4
gpt4 key购买 nike

[Python telnetlib read_until recv问题]

“read_until”函数返回带有长命令的截断字符串。
命令运行完美,但不显示完整文本。
我怎样才能解决这个问题?请帮忙。

#我的代码

tn = telnetlib.Telnet(ip, 23, 5)
prompt = ']# '
tn.write('echo "this is a long command for the test purpose... > test.txt"\n')
print tn.read_until(prompt, 1)

#调试输出

Telnet(192.168.220.4,23): send 'echo "this is a long command for the test purpose... > test.txt"\n'
Telnet(192.168.220.4,23): recv 'echo "this is a l'
Telnet(192.168.220.4,23): recv 'ong command for the test purpose... > te\r\x00 Telnet(192.168.220.4,23): recv 'a long command for the test purpose... > tes '
Telnet(192.168.220.4,23): recv '\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08t.txt"'
Telnet(192.168.220.4,23): recv '\r\n这是一个用于测试目的的长命令...>'
Telnet(192.168.220.4,23): recv 'test.txt\r\n[root@RHEL6-5 tmp]# '

#真实输出

<这是用于测试目的的长命令...> test.txt"
这是用于测试目的的长命令...> test.txt
[root@RHEL6-5 tmp]#

最佳答案

问题似乎是由于换行引起的。我找到了一个解决方案,将窗口大小宽度设置为接近最大值允许接收长行而无需 telnet 服务器应用换行。

(有关设置选项 https://www.ietf.org/rfc/rfc1073.txt 的详细信息,请参阅窗口大小选项 RFC)

import telnetlib
import struct
from telnetlib import DO, DONT, IAC, WILL, WONT, NAWS, SB, SE

MAX_WINDOW_WIDTH = 65000 # Max Value: 65535
MAX_WINDOW_HEIGHT = 5000


def set_max_window_size(tsocket, command, option):
"""
Set Window size to resolve line width issue
Set Windows size command: IAC SB NAWS <16-bit value> <16-bit value> IAC SE
--> inform the Telnet server of the window width and height.
Refer to https://www.ietf.org/rfc/rfc1073.txt
:param tsocket: telnet socket object
:param command: telnet Command
:param option: telnet option
:return: None
"""
if option == NAWS:
width = struct.pack('H', MAX_WINDOW_WIDTH)
height = struct.pack('H', MAX_WINDOW_HEIGHT)
tsocket.send(IAC + WILL + NAWS)
tsocket.send(IAC + SB + NAWS + width + height + IAC + SE)
# -- below code taken from telnetlib source
elif command in (DO, DONT):
tsocket.send(IAC + WONT + option)
elif command in (WILL, WONT):
tsocket.send(IAC + DONT + option)

ip = 'x.x.x.x'
tn = telnetlib.Telnet(ip, 23, timeout=5)
tn.set_option_negotiation_callback(set_max_window_size)

tn.write('echo "this is a long command for the test purpose... > test.txt"\n')

prompt = ']# '
print tn.read_until(prompt, timeout=1)

关于Python telnetlib read_until 返回截断的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38288887/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com