Python telnet 未显示结果

问题描述

使用 python 脚本,我想在 mikrotik 路由器上进行一些配置,看起来脚本是正确的,没有给出错误,但没有打印命令输出就结束了

import telnetlib
import time
dev_ip = "172.16.62.160"
user = "admin"
PASSWORD = ""
comm1 = "ip address print"

tn = telnetlib.Telnet(dev_ip,timeout=1)
tn.read_until(b"Login: ")
tn.write(user.encode("ascii") + b'\n')
tn.read_until(b"Password: ")
tn.write(PASSWORD.encode("ascii") + b'\n')
tn.read_until(b">")
time.sleep(1)
tn.write(comm1.encode("ascii") + b"\r\n")
Showcmdoutput = tn.read_very_eager().decode('ascii')
print(Showcmdoutput)
tn.close()
print("DONE")

在 Ubuntu 桌面上运行

解决方法

放置后问题解决:

time.sleep(1)

Showcmdoutput = tn.read_very_eager().decode('ascii')之前

tn.write(comm1.encode("ascii") + b"\r\n")
time.sleep(1)
Showcmdoutput = tn.read_very_eager().decode('ascii')