A simple Python-based project for managing TP-Link WRxxxN series routers using `requests`. This script handles token generation and allows control of TP-Link WRxxxN routers directly from Python scripts
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

77 lines
2.4 KiB

import time
import logging
import requests
from cookie_tplink_wr_series import get_cookie
from my_secrets import my_secrets
logging.basicConfig(encoding="utf-8", level=logging.INFO) # filename="example.log"
class TPLink(object):
def __init__(self, ip="192.168.0.1", login="", password=""):
self.ip = f"http://{ip}"
self.auth_cookie = get_cookie(login, password)
self.session_id = ""
def login(self):
have_new_sid = False
for _ in range(3):
req = requests.get(
f"{self.ip}/userRpm/LoginRpm.htm?Save=Save",
headers={"Referer": f"{self.ip}/", "Cookie": self.auth_cookie},
)
if req.status_code != 200:
logging.warning(
f"Failed login with token '{self.auth_cookie}' (request code != 200)"
)
continue
params = req.text.split("/")
if len(params) >= 3:
if len(params[3]) == 16:
self.session_id = params[3]
have_new_sid = True
logging.info(f"Successfully login to session {self.session_id}")
break
time.sleep(0.1)
if not have_new_sid:
self.session_id = ""
logging.warning(
f"Failed login with token '{self.auth_cookie}' (can't get session id)"
)
def logout(self):
have_logout = False
for _ in range(3):
req = requests.get(
f"{self.ip}/{self.session_id}/userRpm/LogoutRpm.htm",
headers={
"Referer": f"{self.ip}/{self.session_id}/userRpm/MenuRpm.htm",
"Cookie": self.auth_cookie,
},
)
if req.status_code != 200:
logging.warning(
f"Failed logout from session '{self.session_id}' (request code != 200)"
)
continue
else:
have_logout = True
break
time.sleep(1)
if not have_logout:
self.session_id = ""
logging.warning(f"Failed logout")
else:
logging.info(f"Successfully logout from session {self.session_id}")
router = TPLink(login=my_secrets.login, password=my_secrets.password)
router.login()
router.logout()