gpt4 book ai didi

python3 telnet read_all() 不起作用

转载 作者:行者123 更新时间:2023-11-28 21:39:16 25 4
gpt4 key购买 nike

我正在通过 Python3 远程登录到 Cisco 路由器。但是,它在运行脚本后挂断了(但我能够从我的 Linux bash telnet 到路由器)。请在下面查看我的脚本片段和输出。

import getpass
import telnetlib
HOST = "10.10.32.3"
user = input("Enter your telnet username: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
tn.write(b"conf t\n")
tn.write(b"int l0\n")
print(tn.read_all().decode('ascii'))

这是路由器上debug telnet的输出

Router#
*Nov 2 23:48:24.317: Telnet578: 1 1 251 1
*Nov 2 23:48:24.318: TCP578: Telnet sent WILL ECHO (1)
*Nov 2 23:48:24.318: Telnet578: 2 2 251 3
*Nov 2 23:48:24.318: TCP578: Telnet sent WILL SUPPRESS-GA (3)
*Nov 2 23:48:24.318: Telnet578: 80000 80000 253 24
*Nov 2 23:48:24.319: TCP578: Telnet sent DO TTY-TYPE (24)
*Nov 2 23:48:24.319: Telnet578: 10000000 10000000 253 31
*Nov 2 23:48:24.319: TCP578: Telnet sent DO WINDOW-SIZE (31)
*Nov 2 23:48:24.383: TCP578: Telnet received DONT ECHO (1)
*Nov 2 23:48:24.383: TCP578: Telnet sent WONT ECHO (1)
*Nov 2 23:48:24.387: TCP578: Telnet received DONT SUPPRESS-GA (3)
*Nov 2 23:48:24.387: TCP578: Telnet sent WONT SUPPRESS-GA (3)
Router#
*Nov 2 23:48:24.389: TCP578: Telnet received WONT TTY-TYPE (24)
*Nov 2 23:48:24.389: TCP578: Telnet sent DONT TTY-TYPE (24)
*Nov 2 23:48:24.390: TCP578: Telnet received WONT WINDOW-SIZE (31)
*Nov 2 23:48:24.391: TCP578: Telnet sent DONT WINDOW-SIZE (31)
*Nov 2 23:48:24.407: TCP578: Telnet received DONT ECHO (1)
*Nov 2 23:48:24.407: TCP578: Telnet received DONT SUPPRESS-GA (3)
*Nov 2 23:48:24.407: TCP578: Telnet received WONT TTY-TYPE (24)
*Nov 2 23:48:24.408: TCP578: Telnet received WONT WINDOW-SIZE (31)

show tcp brief的输出

Router#sho tcp brief 
TCB Local Address Foreign Address (state)
10C90CE0 10.10.32.3.23 192.168.122.61.51466 ESTAB

我可以创建环回接口(interface),但我的 Linux bash 没有显示 telnet 输出。请相应指导。谢谢。

最佳答案

telnetlib 中的

.read_all() 被记录为“读取所有数据直到 EOF;阻塞直到连接关闭。”。因为您没有做任何会导致连接关闭的事情,所以挂起正是您应该期望在这里发生的事情。尝试先向路由器发送退出命令。或者,如果您打算根据读取的结果发出更多命令,请改用 .read_until()(可能指定超时)。

关于python3 telnet read_all() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47087138/

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