How to control a TPLINK router with a python script

sadek picture sadek · Mar 13, 2013 · Viewed 16.4k times · Source

I wanted to know whether there is a tool that allows me to connect to a router and shut it down, and then reboot it from a python script.

I know that if I write in a python script: import os and then do os.system("ssh -l root 192.168.2.1"), I can connect through python to my router. But then, I don't know how to apply the router's password, and to log into it, in order to reboot it.

So after working on it a bit here is the code that I have written in order to connect to my router with an SSH session using a python script:

    import os, urllib, urllib2, re

    def InterfaceControl():
       #os.system("echo training")
       os.system("ssh -l root 192.168.2.1")
       os.system("echo yes")
       os.system("echo My_ROUTER_PASSWORD")
       os.system("shutdown -r")



     def main():
         InterfaceControl()


     if __name__=="__main__":
         main()

The problem is that I still can not connect to my router with this code, and moreover, IDLE (the editor I use to write and run python script) crashes. Can anyone help me improve this code?

Answer

Alex Gluhov picture Alex Gluhov · Nov 30, 2017

It depends on your tplink device model and firmware, because auth algorithm differ from model to model. I wrote that python script, that works fine for my tp link W740N. The code explains how to authenticate on this device using requests package

#!/usr/bin/python3
# imports
from requests import get
from base64 import b64encode
from urllib.parse import quote


# constants
tplink = '192.168.0.1'
user = 'admin'
password = 'admin'
url_template = 'http://{}/userRpm/SysRebootRpm.htm?Reboot=Reboot'


if __name__ == '__main__':
    auth_bytes = bytes(user+':'+password, 'utf-8')
    auth_b64_bytes = b64encode(auth_bytes)
    auth_b64_str = str(auth_b64_bytes, 'utf-8')

    auth_str = quote('Basic {}'.format(auth_b64_str))

    auth = {
    'Referer': 'http://'+tplink+'/', 
    'Authorization': auth_str,
    }

    reboot_url = url_template.format(tplink)

    r = get(reboot_url, headers=auth)