Python 3 telnetlib路由器重新启动



我正在尝试编写一个python脚本来重新启动我的路由器。

我可以用普通的telnet很好地做到这一点,但是,在python代码中,由于某种原因,除非我在代码底部添加tn.read_all((,否则不会执行重新启动操作。这是当前的工作代码:

import sys
import telnetlib
import time
HOST = "192.168.0.1"
password = "12345678"
try:
with telnetlib.Telnet(HOST,23,timeout=10) as tn:
print(tn.read_until(b'password:', 5))
tn.write((password + 'rn').encode('ascii'))
print(tn.read_until(b'(conf)#', 5))
tn.write(('dev reboot' + 'rn').encode('ascii'))
time.sleep(1)
print(tn.read_all().decode('ascii'))

except EOFError:
print("Unexpected response from router")
except ConnectionRefusedError:
print("Connection refused by router. Telnet enabled?")
except:
print("Error")

telnet操作的正常输出为:

--------------------------------------------------------------------------------
Welcome To Use TP-Link COMMAND-LINE Interface Model.
--------------------------------------------------------------------------------
TP-Link(conf)#dev reboot
[ oal_sys_reboot ] 489:  now sleep for 2 secs
TP-Link(conf)#killall: pppd: no process killed

保持read_all((使操作超时,同时打印";错误";在例外中定义。我想保持这个干净和简单。我怎样才能做到这一点?

显然,延迟不够,连接很快就关闭了。添加read_all是为了保持连接处于打开状态,因此在添加连接时会执行命令。解决方案是将延迟从1秒增加到5秒。


import sys
import telnetlib
import time
HOST = "192.168.0.1"
password = "12345678"
port = 23
try:
print('Opening Telnet Connection to Router.')
with telnetlib.Telnet(HOST,port,timeout=10) as tn:
tn.read_until(b'password:', 10)
print('Sending password to Router.')
tn.write((password + 'rn').encode('ascii'))
time.sleep(1)
tn.read_until(b'(conf)#', 10)
print('Rebooting the Router!!!')
tn.write(('dev reboot' + 'rn').encode('ascii'))
time.sleep(5)

except EOFError:
print("Unexpected response from router")
except ConnectionRefusedError:
print("Connection refused by router. Telnet enabled?")
except:
print("Error")

最新更新