I am trying to write a python script to reboot my router.
I can do this just fine with normal telnet, however, in the python code, for some reason, unless I add tn.read_all() to the bottom of the code, reboot operation does not execute. Here is the current working code:
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 + '\r\n').encode('ascii'))
print(tn.read_until(b'(conf)#', 5))
tn.write(('dev reboot' + '\r\n').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")
The normal output for the telnet operation is:
--------------------------------------------------------------------------------
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
Keeping read_all() makes the operation timeout with printing "error" defined in the exceptions. I want to keep this clean and simple. How can I achieve this?
Apparently, the delay was not enough and the connection was closing quickly. Adding read_all was keeping the connection open so commands executed when it was added. Solution was to increase the delay from 1s to 5s.
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 + '\r\n').encode('ascii'))
time.sleep(1)
tn.read_until(b'(conf)#', 10)
print('Rebooting the Router!!!')
tn.write(('dev reboot' + '\r\n').encode('ascii'))
time.sleep(5)
except EOFError:
print("Unexpected response from router")
except ConnectionRefusedError:
print("Connection refused by router. Telnet enabled?")
except:
print("Error")