Control TPLink router with Python

Python APIs to control TPLink router

Probhakar
2 min readMay 10, 2021

I was doing a project for which I needed to do MAC whitelisting to my TPLink router. The only way to do that was through TPLink webpage at 192.168.0.1.

So I wrote a python module so that I can use it to control my router. It is very well documented.

Before using the module make sure you have installed python requests library.

Download or clone the file from https://github.com/epsi95/TPLink-Python

You can see a file named tplink_python.py

Place it in your directory where is your python file is, and then import it as

from tplink_python import TPLinkClient

To start using it

>>> tp_client = TPLinkClient(username='admin', password='admin', router_url='192.168.0.1')
>>> internet_link_status = tp_client.check_internet_link_status()
>>> print('router can connect to IPS: ' + str(internet_link_status.upper() == 'UP'))
Output
-------
router can connect to IPS: True

Change username and password to whatever you use to log in to your router. There are many APIs available, all are documented on the above-mentioned GitHub Page.

For example to get the list of devices connected to your wifi

>>> all_connected_devices = tp_client.get_wireless_connected_devices()
>>> print(all_connected_devices)
Output
-------
[
{
'associatedDeviceMACAddress': 'a7:ea:b4:c0:1b:e8',
'X_TP_TotalPacketsSent': '328263',
'X_TP_TotalPacketsReceived': '52826',
'X_TP_HostName': 'wlan0'
}
]

To whitelist a MAC address

>>> mac_whitelist_result = tp_client.whitelist_mac("02:00:00:%02x:%02x:%02x" % (random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255)), "temporary")
>>> if "[error]0" not in mac_whitelist_result:
print("whitelisting not successful", mac_whitelist_result)
else:
print("whitelisting successful")
Output
-------
whitelisting successful

To remove a MAC from whitelisting

remove_result = tp_client.remove_mac_from_whitelist(mac_address)
if "[error]0" in remove_result:
print("MAC removal is successful")

--

--