Skip to content

Instantly share code, notes, and snippets.

@vicwomg
Last active September 6, 2024 11:25
Show Gist options
  • Save vicwomg/9b0bc6f1ea22e08379651a36877e0420 to your computer and use it in GitHub Desktop.
Save vicwomg/9b0bc6f1ea22e08379651a36877e0420 to your computer and use it in GitHub Desktop.
@zambaraa
Copy link

main()
   ^

IndentationError: expected an indented block

@maxammann
Copy link

@zambaraa I think you should use python2

@maxammann
Copy link

@vicwomg thank you soo much! Working on 3.16.9 Build 20160607 Rel.58297n

Just saved me from clicking though 20 routers :)

Copy link

ghost commented Apr 22, 2019

Is there a possibilty to convert this in Python3? ive tries it myself, but keep hitting walls of my knowlegde

@Paul595
Copy link

Paul595 commented Jun 11, 2020

Someone having a working version for the HW Version 5 and Firmware 190726?

@rndazurescript
Copy link

rndazurescript commented Jul 31, 2020

Python v3 but I am in an earlier firmware version and in my case, I had to pass an Authorization header:

import requests
import base64
import sys


ROUTER_IP = "192.168.0.1"
USERNAME = "admin"
PASSWORD = "YOUR_ROUTER_PASSWORD_HERE"

class TPLink_Archer_C7_Router_Web_Interface:
	""" Class for scraping/navigating the TPLink Archer C7 Router Web UI. Originally for
	the purpose of scheduling reboots using cron. Can probably be extended to automate
	many other functions in the web UI with a little bit of snooping around the html.
	
	Only tested on the Archer C7, but I imagine there's a good chance it would work on 
	other models if they use the same Web UI. 
	
	https://github.com/vicwomg
	"""

	def __init__(self, router_ip, username, password):
		self.latest_tested_version = "3.13.34 Build 131217 Rel.60903n"
		
		self.login_url = "http://%s/userRpm/StatusRpm.htm"
		self.reboot_url_path = "/userRpm/SysRebootRpm.htm?Reboot=Reboot"
		self.referer = f"http://{router_ip}/userRpm/MenuRpm.htm"
		self.router_ip = router_ip
		self.username = username
		self.password = password
		
	def login(self):
		print("Logging in to router...")
		self.authHeader = self.get_auth_header()
		self.test_credentials()

	def get_auth_header(self):
		data = (self.username + ":" + self.password)
		encodedBytes = base64.b64encode(data.encode("utf-8"))
		encodedStr = str(encodedBytes, "utf-8")
		authHeader = "Basic " + encodedStr
		return authHeader
	
	def get_headers(self):
	    return {
		  'Authorization': self.authHeader,
		  'Referer': self.referer
		}
    
	def test_credentials(self):    
		print(f"Authorization header: {self.authHeader}.")
		url= self.login_url % self.router_ip
		print(f"Requesting at {url}")
		output = requests.get(url, headers=self.get_headers()).text
		if (self.router_ip in output):
			print(f"Logged in: {output}")
		else: 
			print("ERROR: Failed to scrape out session url. ")
			print("Server response:")
			print(output)
			print("  Bad username/password? ")
			print("  Or you're already logged in to the admin interface somewhere else?")
			print("  Or perhaps unsupported web UI firmware. Last tested on: " + self.latest_tested_version)
			sys.exit(1)
		
	def reboot(self):
		reboot_command_url =  f"http://{self.router_ip}{self.reboot_url_path}"
		print(f"Rebooting router with: {reboot_command_url} ...")
		
		output = requests.get(reboot_command_url, headers=self.get_headers()).text
		
		print("Reboot command sent. Response was:")
		print(output)
		
def main():
	tp = TPLink_Archer_C7_Router_Web_Interface(ROUTER_IP, USERNAME, PASSWORD)
	tp.login()
	tp.reboot()
	
if __name__ == "__main__":
	main()

@pacastro
Copy link

pacastro commented Aug 8, 2020

the v3 version is not working for me, i have Archer C7 firmware 3.15.3 Build 180114 Rel.39265n
no much knowledge on python so no way I can figure out why its not working, the python v2 version works fine for me (same Archer firmware)...was looking forward to upgrade to python v3

@alansenairj
Copy link

import requests
import base64
import sys


ROUTER_IP = "192.168.0.1"
USERNAME = "admin"
PASSWORD = "YOUR_ROUTER_PASSWORD_HERE"

class TPLink_Archer_C7_Router_Web_Interface:
	""" Class for scraping/navigating the TPLink Archer C7 Router Web UI. Originally for
	the purpose of scheduling reboots using cron. Can probably be extended to automate
	many other functions in the web UI with a little bit of snooping around the html.
	
	Only tested on the Archer C7, but I imagine there's a good chance it would work on 
	other models if they use the same Web UI. 
	
	https://github.com/vicwomg
	"""

	def __init__(self, router_ip, username, password):
		self.latest_tested_version = "3.13.34 Build 131217 Rel.60903n"
		
		self.login_url = "http://%s/userRpm/StatusRpm.htm"
		self.reboot_url_path = "/userRpm/SysRebootRpm.htm?Reboot=Reboot"
		self.referer = f"http://{router_ip}/userRpm/MenuRpm.htm"
		self.router_ip = router_ip
		self.username = username
		self.password = password
		
	def login(self):
		print("Logging in to router...")
		self.authHeader = self.get_auth_header()
		self.test_credentials()

	def get_auth_header(self):
		data = (self.username + ":" + self.password)
		encodedBytes = base64.b64encode(data.encode("utf-8"))
		encodedStr = str(encodedBytes, "utf-8")
		authHeader = "Basic " + encodedStr
		return authHeader
	
	def get_headers(self):
	    return {
		  'Authorization': self.authHeader,
		  'Referer': self.referer
		}
    
	def test_credentials(self):    
		print(f"Authorization header: {self.authHeader}.")
		url= self.login_url % self.router_ip
		print(f"Requesting at {url}")
		output = requests.get(url, headers=self.get_headers()).text
		if (self.router_ip in output):
			print(f"Logged in: {output}")
		else: 
			print("ERROR: Failed to scrape out session url. ")
			print("Server response:")
			print(output)
			print("  Bad username/password? ")
			print("  Or you're already logged in to the admin interface somewhere else?")
			print("  Or perhaps unsupported web UI firmware. Last tested on: " + self.latest_tested_version)
			sys.exit(1)
		
	def reboot(self):
		reboot_command_url =  f"http://{self.router_ip}{self.reboot_url_path}"
		print(f"Rebooting router with: {reboot_command_url} ...")
		
		output = requests.get(reboot_command_url, headers=self.get_headers()).text
		
		print("Reboot command sent. Response was:")
		print(output)
		
def main():
	tp = TPLink_Archer_C7_Router_Web_Interface(ROUTER_IP, USERNAME, PASSWORD)
	tp.login()
	tp.reboot()
	
if __name__ == "__main__":
	main()

ERROR: Failed to scrape out session url.

@jrwren
Copy link

jrwren commented Nov 13, 2021

None of the python was working for me so I ported it to bash, curl, coreutils

#!/bin/bash
IP=192.168.0.1
USER=admin
PASSWD=YOURPASSWORDHERE

LOGIN_URL=http://$IP/userRpm/LoginRpm.htm?Save=Save
REBOOT_PATH=/userRpm/SysRebootRpm.htm

PASSMD5=$(echo -n $PASSWD | md5sum | cut -f 1 -d ' ')
COOKIE="Authorization=Basic%20$(echo -n "$USER:$PASSMD5" | base64|sed s/=/%3D/)"

SESSION=$(curl -s -b "$COOKIE" "$LOGIN_URL" | grep -o 'http://[^"]*')
REBOOT_URL="$(dirname $(dirname $SESSION))$REBOOT_PATH"
curl -sif -o /dev/null -b "$COOKIE" -e "$REBOOT_URL" "$REBOOT_URL?Reboot=Reboot"

@Gerrelt
Copy link

Gerrelt commented Dec 23, 2021

Thanks jrwren, that bash script works like a charm on my TP link Archer C7 v2!

One thing to note: you cannot be logged into the web-interface while running this script.
Apparently only one admin can be logged in at a time.
I thought the script wasn't working, but it was because I was logged in via the browser. After logging out, it worked.

@Gerrelt
Copy link

Gerrelt commented Dec 26, 2021

During testing, sometimes the reboot wasn't working, which meant admin stayed logged in.
I've added this to the end of the script, to logout admin if the reboot didn't work:

# if the reboot didn't work:
LOGOUT_URL="$(dirname $(dirname $SESSION))/userRpm/LogoutRpm.htm"
curl -sif -o /dev/null -b "$COOKIE" -e "$LOGOUT_URL" "$LOGOUT_URL"

@knorr-goose
Copy link

Hi !!! Wonderful info... Does anybody know where is the doc to navigate menus, or get a list of connected MACs... I want to discover unauthorized MACs and log them out? Maybe it is not possible... Thanks in advance for your help !!!

@bit7777
Copy link

bit7777 commented Sep 25, 2022

Here comes a modified version of the script from @jrwren for use on a TP-Link Archer C7 V1 with the latest Firmware 3.15.3 Build 150511 Rel.5581:

#!/bin/bash
IP=192.168.0.1
USER=admin
PASSWD=YOURPASSWORDHERE

LOGIN_URL=http://$IP/userRpm/LoginRpm.htm?Save=Save
REBOOT_PATH=/userRpm/SysRebootRpm.htm

#PASSMD5=$(echo -n $PASSWD | md5sum | cut -f 1 -d ' ')
#COOKIE="Authorization=Basic%20$(echo -n "$USER:$PASSMD5" | base64|sed s/=/%3D/)"

COOKIE="Authorization=Basic%20$(echo -n "$USER:$PASSWD" | base64|sed s/=/%3D/g)"

SESSION=$(curl -s -b "$COOKIE" "$LOGIN_URL" | grep -o 'http://[^"]*')
REBOOT_URL="$(dirname $(dirname $SESSION))$REBOOT_PATH"
curl -sif -o /dev/null -b "$COOKIE" -e "$REBOOT_URL" "$REBOOT_URL?Reboot=Reboot"

I was also able to write this script in a version running with cmd.exe on Windows XP SP3 (no cygwin etc. required). If someone is interested I can post it here.

@ausfas
Copy link

ausfas commented Sep 6, 2024

Here comes a modified version of the script from @jrwren for use on a TP-Link Archer C7 V1 with the latest Firmware 3.15.3 Build 150511 Rel.5581:

#!/bin/bash
IP=192.168.0.1
USER=admin
PASSWD=YOURPASSWORDHERE

LOGIN_URL=http://$IP/userRpm/LoginRpm.htm?Save=Save
REBOOT_PATH=/userRpm/SysRebootRpm.htm

#PASSMD5=$(echo -n $PASSWD | md5sum | cut -f 1 -d ' ')
#COOKIE="Authorization=Basic%20$(echo -n "$USER:$PASSMD5" | base64|sed s/=/%3D/)"

COOKIE="Authorization=Basic%20$(echo -n "$USER:$PASSWD" | base64|sed s/=/%3D/g)"

SESSION=$(curl -s -b "$COOKIE" "$LOGIN_URL" | grep -o 'http://[^"]*')
REBOOT_URL="$(dirname $(dirname $SESSION))$REBOOT_PATH"
curl -sif -o /dev/null -b "$COOKIE" -e "$REBOOT_URL" "$REBOOT_URL?Reboot=Reboot"

I was also able to write this script in a version running with cmd.exe on Windows XP SP3 (no cygwin etc. required). If someone is interested I can post it here.

I'm not an expert in Linux, can you please post the script that I run and test in Windows before testing if it can work in Homeassistant ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment