Last active
December 18, 2015 13:09
-
-
Save blha303/5788199 to your computer and use it in GitHub Desktop.
ISP usage checker / router disabler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2.7 | |
version = "r7" | |
# This script gets usage from my ISP's website, checks to see if the current average for the month | |
# is above their recommended amount per day, then disables the wifi on my router if it is. | |
# I made this for a household of people who don't understand the consequences of their actions | |
# (namely, that if you abuse our awesome internet, we all have to suffer with being shaped :( ) | |
# Please, modify this for your own ISP/router and set it up in your own house to help with your daily usage. | |
# -blha303 | |
# Usage: python westnetusage.py [debug] | |
# Options: | |
# username = Westnet username | |
# password = Westnet password | |
# routerpass = BoB2 router password | |
# always_on_wireless_computer = A laptop or some other device that's always turned on, and connected to the wireless network. | |
# and also running a web server (http://address needs to be accessible) | |
# timezone = Timezone for logs, in format <country>/<city> | |
# BSD license. | |
username = "USERNAME" | |
password = "PASSWORD" | |
routerpass = "" | |
always_on_wireless_computer = "ip or hostname" | |
timezone = "Australia/Perth" | |
import urllib2 | |
from BeautifulSoup import BeautifulSoup | |
import urllib | |
import cookielib | |
import time | |
from sys import argv | |
import os | |
debug = False | |
try: | |
if argv[1] == "debug": | |
debug = True | |
except IndexError: | |
debug = False | |
def debug(msg): | |
if debug: | |
print msg | |
debug("Debug active") | |
def getnumbers(inp): # For parsing "100,000MB" to an integer | |
return int(inp[:-2].replace(",", "")) | |
debug("getnumbers function set") | |
url = "https://myaccount2.westnet.com.au/" # login page url | |
desc = "westnet usage alert script %s by blha303. https://gist.github.com/blha303/5788199 for source" % version # what the server sees as the client ID | |
debug("url, desc variables set") | |
logindata = urllib.urlencode({"hdnLoginType": "myaccount", "action": "login", "username": username, "password": password}) # login POST data | |
debug("logindata set") | |
cj = cookielib.CookieJar() # Cookie jar, used to store login session | |
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) | |
debug("cookie jar set") | |
opener.addheaders = [('User-Agent', desc)] # set client ID to desc | |
debug("user agent set") | |
login = opener.open(url, logindata) # log in, save session data to cookie jar | |
debug("logged into westnet") | |
page = opener.open(url) # reopen same url (westnet has both login and homepage on the same url) | |
debug("loaded usage page") | |
soup = BeautifulSoup(page.read()) # make soup from page | |
debug("made soup") | |
usage = soup.findAll('div',{'class':'usage_text'})[0].text # get usage string "XXX,XXXMB out of XXX,XXXMB" | |
debug("found usage string") | |
count = getnumbers(usage.split(" ")[0]) # get count integer, first part of usage string above as integer | |
debug("found count") | |
total = getnumbers(usage.split(" ")[-1]) # get total integer, last part of usage string above as integer | |
debug("found total") | |
suggested = getnumbers(soup.findAll('a',{'href':'#suggested_anytime_tooltip'})[0].text) # get suggested integer | |
debug("found suggested") | |
trend = getnumbers(soup.findAll('a',{'href':'#trend_anytime_tooltip'})[0].text) # get trend integer | |
debug("found trend") | |
debug("usage: " + usage) | |
debug("count: " + str(count)) | |
debug("total: " + str(total)) | |
debug("suggested: " + str(suggested)) | |
debug("trend: " + str(trend)) | |
boblogin = "http://10.1.1.1/login.cgi" # router login url | |
bobdata = urllib.urlencode({"login_option": "0", "password": routerpass, "passwordtemp": ""}) # router login info as POST data | |
debug("set up bob login data") | |
wdisurl = "http://10.1.1.1/wireless_id.wl?wlSsidIdx=0&wlEnbl=0" # router disable wireless url as GET data | |
wenurl = "http://10.1.1.1/wireless_id.wl?wlEnbl=1&wlSsidIdx=0" # router enable wireless url as GET data | |
debug("set up bob wireless urls") | |
os.environ['TZ'] = timezone | |
time.tzset() | |
if debug: | |
ts = time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.localtime()) # timestamp for status webpage | |
else: | |
ts = time.strftime("%a, %d %b %Y %H:00:00 %Z", time.localtime()) # as the script is called automatically every hour on the hour, minutes and seconds aren't needed | |
debug("set up timestamp") | |
def logintoBob(): | |
opener.open(boblogin, bobdata) # log into router, save session to cookie jar | |
debug("set up logintoBob") | |
def enableWireless(f): | |
try: | |
wireless_test = urllib2.urlopen("http://%s" % always_on_wireless_computer).getcode() | |
debug("Found %s, not re-enabling wireless (avoids annoying disconnection issue)" % always_on_wireless_computer) | |
except urllib2.URLError: | |
debug("Couldn't find %s, telling the router to enable wireless" % always_on_wireless_computer) | |
logintoBob() | |
debug("logged into bob") | |
opener.open(wenurl) # send wireless enable request using login info from cookiejar | |
debug("Wireless enabled. connection may die for a few seconds") | |
f.write("%s: Enable wireless %s %s/%s\n" % (ts, usage, str(trend), str(suggested))) | |
debug("wrote to /var/www/westnet.html") | |
debug("set up enableWireless") | |
def disableWireless(f): | |
logintoBob() | |
debug("logged into bob") | |
opener.open(wdisurl) # send wireless disable request using login info from cookiejar | |
debug("wireless disabled") | |
f.write("%s: Disable wireless %s %s/%s\n" % (ts, usage, str(trend), str(suggested))) | |
debug("wrote to /var/www/westnet.html") | |
debug("set up disableWireless") | |
if count > total: | |
shaped = True | |
else: | |
shaped = False | |
debug("shaped: " + str(shaped)) | |
f = open("/var/www/westnet.html", "a") # Append to web-accessible file | |
debug("/var/www/westnet.html opened for appending") | |
if trend > suggested and not shaped: | |
debug("disabling wireless") | |
disableWireless(f) | |
elif shaped or trend <= suggested: | |
debug("enabling wireless") | |
enableWireless(f) | |
debug("closing file") | |
f.close() | |
debug("finished") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment