Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import time
- import subprocess
- import urllib
- import urllib2
- import socket
- import re
- import optparse
- # DEFAULT ROUTER CREDENTIALS
- ROUTER_IP = '192.168.1.1'
- ROUTER_USER = "admin"
- ROUTER_PWD = "password"
- ROUTER_PAGE = 'HTTP://'+ROUTER_IP
- # Command line arguments override!
- argparser = optparse.OptionParser()
- # router username..
- argparser.add_option("-u", "--user", action="store",type="string",dest="user",help="Router Login Username",metavar="USER",)
- # router password
- argparser.add_option("-p", "--pwd", action="store",type="string",dest="password",help="Password For The Router User account",metavar="PWD")
- # router ip address
- argparser.add_option("-a", "--ip", action="store", type="string", dest="host",help="Address To The Router", metavar="IP")
- (argoptions, args) = argparser.parse_args()
- if argoptions.user:
- ROUTER_USER = argoptions.user
- if argoptions.password:
- ROUTER_PWD = argoptions.password
- if argoptions.host:
- ROUTER_IP = argoptions.host
- ROUTER_PAGE = 'HTTP://'+ROUTER_IP
- RIP=ROUTER_IP.split(".")[0]+"."+ROUTER_IP.split(".")[1]+"."+ROUTER_IP.split(".")[2]
- def get_own_lanip():
- ''' the the ip of the computer running this program'''
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- s.connect((ROUTER_IP,80))
- ip = (s.getsockname()[0])
- s.close()
- return ip
- def router_login():
- ''' login to the ROUTER_IP using basic http auth. will return true/false on successfull login.'''
- authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
- authinfo.add_password(None, ROUTER_IP, ROUTER_USER, ROUTER_PWD)
- handler = urllib2.HTTPBasicAuthHandler(authinfo)
- myopener = urllib2.build_opener(handler)
- opened = urllib2.install_opener(myopener)
- try:
- output = urllib2.urlopen(ROUTER_PAGE)
- content = output.read()
- if output:
- return True
- except:
- return False
- def router_getPage_WLG_wireless():
- '''Request the Wireless Settings ROUTER_PAGE and retrun the content.'''
- output = urllib2.urlopen(ROUTER_PAGE+"/WLG_wireless.htm")
- content = output.read()
- print "Collecting wifi settings...!"
- # # # # # # # # # # # # # # # # # # # # # #
- # Search the content using regex.
- # pages that the router redirects the browser to based on its settings.
- wifipages = {
- "Auto" : "WLG_wireless1.htm",
- "Shared-Key" : "WLG_wireless1.htm",
- "WPA-PSK" : "WLG_wireless2.htm",
- "WPA2-PSK" : "WLG_wireless2.htm",
- "WPA-AUTO-PSK" : "WLG_wireless2.htm",
- "Open-System" : "WLG_wireless3.htm"
- }
- # # # # # # # # # # # # # # # # # # # # # #
- # Get Wep status!
- patternwep = re.compile(r'var\swepStatus="(.+)";')
- swep = patternwep.search(content)
- wepstat = swep.groups()[0]
- # # # # # # # # # # # # # # # # # # # # # #
- # Get Auth Type!
- patternauth = re.compile(r'var\sauthType="(.+)";')
- authtype = patternauth.search(content).groups()[0]
- # # # # # # # # # # # # # # # # # # # # # # # #
- # ONLY WPA-PSK/WPA2 SUPPORTED.
- # Did not bother with old wep since i never use it.
- if authtype == "Auto" or authtype == "Open-System" or authtype == "Shared-Key" or authtype == "Open-System":
- print "Wep:",wepstat,"and", authtype,"security is not supported.. change security to WPA-PSK/WPA2-PSK"
- return False
- # # # # # # # # # # # # # # # # # # # # # # # #
- # # # # # # # # # # # # # # # # # # # # # #
- # Get the new page content!.. WLG_wireless2.htm
- #output = urllib2.urlopen(ROUTER_PAGE+"/"+wifipages[authtype])
- output = urllib2.urlopen(ROUTER_PAGE+"/WLG_wireless2.htm")
- content = output.read()
- #print content
- # # # # # # # # # # # # # # # # # # # # # #
- # SSID.
- # '<input type="text" name="ssid" value="hula" size="20" maxlength="32">'
- # '<input name="ssid" value="hula" size="20" maxlength="32" type="text">'
- # Content is not static and vary that why the ugly code below.
- ssid_pattern = re.compile(r'<inp.+ name="ssid".+value=(.+)>')
- ssid_value = ssid_pattern.search(content).groups()[0].replace('maxlength="32"', "").replace('size="20"',"").replace('type="text"', "")
- ssid_value = ssid_value[::-1][ssid_value[::-1].index('"')::]
- ssid_value = ssid_value[1: len(ssid_value)-1][::-1]
- print "SSID:", ssid_value
- # # # # # # # # # # # # # # # # # # # # # #
- # REGION.
- region_pattern = re.compile(r'<inp.+ name="tempRegion".+value="(\d+)".+')
- region_value = region_pattern.search(content).groups()[0]
- print "REGION:", region_value
- # # # # # # # # # # # # # # # # # # # # # #
- # CHANNEL.
- channel_pattern = re.compile(r'<inp.+ name="initChannel".+value="(\d+)".+')
- channel_value = channel_pattern.search(content).groups()[0]
- print "CHANNEL:",channel_value
- # # # # # # # # # # # # # # # # # # # # # #
- # MODE.
- mode_pattern = re.compile(r'<select name="opmode".+;">(.+)</select>')
- modes = mode_pattern.search(content).groups()[0]
- mode_option_pattern = re.compile(r'.+<option value=(.+ selected)', re.M)
- mode_value = mode_option_pattern.search(modes).groups()[0].replace(" selected", "")
- mode_value = mode_value[1:len(mode_value)-1]
- print "MODE:",mode_value
- # post data values needed. tried to look at the source but ended up using wireshark instead.
- # not tested but i belive pfChanged is set to 1 when the pwd gets changed
- # so, when this is not changed we can leave the passphrase with *
- values = {
- "ssid" : ssid_value,
- "w_channel" : channel_value,
- "opmode" : mode_value,
- "security_type" : authtype,
- "passphrase" : "********",
- "Apply" : "Apply",
- "initChannel" : channel_value,
- "pfChanged" : "0",
- "tempSetting" : "0",
- "tempRegion" : region_value
- }
- data = urllib.urlencode(values)
- req = urllib2.Request(url=ROUTER_PAGE+"/wireless.cgi",data=data)
- content = urllib2.urlopen(req).read()
- print "Sending wifi reset request..!"
- def ping(ip):
- '''Ping a computer using the system ping command, return True/False if got a respond.
- Does retry a ping one time if it fails on the 1st attempt.
- '''
- retry = 0
- while retry < 1:
- with open(os.devnull, "wb") as void:
- result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip], stdout=void, stderr=void).wait()
- if result:
- if retry < 1:
- retry = 1
- else:
- return False
- else:
- retry = 1
- return True
- def long_wait():
- print "Doing some sleep for 5 min...!"
- time.sleep(60*5)
- main()
- def main():
- '''doc'''
- print "Started router monitor/resetter...!"
- print "Testing Router Login."
- if not router_login():
- print "Login Failed"
- else:
- print "Login Successful."
- router_getPage_WLG_wireless()
- print "Started network checking"
- ownip = get_own_lanip()
- retry = 0
- while 1:
- try:
- time.sleep(20)
- iplist=[]
- #ip range from n.n.n.n - n.n.n.(n+11)
- # ping each client
- for n in range(2,11,1):
- ip=RIP+"."+str(n)
- if ownip != ip and ROUTER_IP != ip:
- iplist.append( ping(ip) )
- #print iplist
- # Reset the wifi on the router if we have less than 1 active.
- # try at reset 3 time.
- if iplist.count(1) < 1:
- if retry < 3:
- succsess = router_login()
- if succsess:
- router_getPage_WLG_wireless()
- else:
- print "Router Login failed"
- time.sleep(45)
- retry+=1
- else:
- long_wait()
- break
- else:
- retry=0
- except KeyboardInterrupt:
- print "Quiting...!"
- break
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement