Advertisement
Guest User

Untitled

a guest
Oct 12th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.23 KB | None | 0 0
  1.  
  2. import os
  3. import time
  4. import subprocess
  5. import urllib
  6. import urllib2
  7. import socket
  8. import re
  9. import optparse
  10.  
  11.  
  12. # DEFAULT ROUTER CREDENTIALS
  13. ROUTER_IP = '192.168.1.1'
  14. ROUTER_USER = "admin"
  15. ROUTER_PWD = "password"
  16. ROUTER_PAGE = 'HTTP://'+ROUTER_IP
  17.  
  18.  
  19. # Command line arguments override!
  20. argparser = optparse.OptionParser()
  21. # router username..
  22. argparser.add_option("-u", "--user", action="store",type="string",dest="user",help="Router Login Username",metavar="USER",)
  23. # router password
  24. argparser.add_option("-p", "--pwd", action="store",type="string",dest="password",help="Password For The Router User account",metavar="PWD")
  25. # router ip address
  26. argparser.add_option("-a", "--ip", action="store", type="string", dest="host",help="Address To The Router", metavar="IP")
  27. (argoptions, args) = argparser.parse_args()
  28.  
  29.  
  30. if argoptions.user:
  31.     ROUTER_USER = argoptions.user
  32. if argoptions.password:
  33.     ROUTER_PWD = argoptions.password
  34. if argoptions.host:
  35.     ROUTER_IP = argoptions.host
  36.  
  37.    
  38. ROUTER_PAGE = 'HTTP://'+ROUTER_IP
  39. RIP=ROUTER_IP.split(".")[0]+"."+ROUTER_IP.split(".")[1]+"."+ROUTER_IP.split(".")[2]
  40.  
  41.  
  42. def get_own_lanip():
  43.     ''' the the ip of the computer running this program'''
  44.     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  45.     s.connect((ROUTER_IP,80))
  46.     ip = (s.getsockname()[0])
  47.     s.close()
  48.     return ip
  49.  
  50. def router_login():
  51.     ''' login to the ROUTER_IP using basic http auth. will return true/false on successfull login.'''
  52.     authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
  53.     authinfo.add_password(None, ROUTER_IP, ROUTER_USER, ROUTER_PWD)
  54.     handler = urllib2.HTTPBasicAuthHandler(authinfo)
  55.     myopener = urllib2.build_opener(handler)
  56.     opened = urllib2.install_opener(myopener)
  57.    
  58.     try:
  59.         output = urllib2.urlopen(ROUTER_PAGE)
  60.         content = output.read()
  61.         if output:
  62.             return True
  63.     except:
  64.         return False
  65.  
  66. def router_getPage_WLG_wireless():
  67.     '''Request the Wireless Settings ROUTER_PAGE and retrun the content.'''
  68.     output = urllib2.urlopen(ROUTER_PAGE+"/WLG_wireless.htm")
  69.     content = output.read()
  70.     print "Collecting wifi settings...!"
  71.    
  72.     # # # # # # # # # # # # # # # # # # # # # #
  73.     # Search the content using regex.
  74.     # pages that the router redirects the browser to based on its settings.
  75.     wifipages = {
  76.         "Auto" : "WLG_wireless1.htm",
  77.         "Shared-Key" : "WLG_wireless1.htm",
  78.         "WPA-PSK" : "WLG_wireless2.htm",
  79.         "WPA2-PSK" : "WLG_wireless2.htm",
  80.         "WPA-AUTO-PSK" : "WLG_wireless2.htm",
  81.         "Open-System" : "WLG_wireless3.htm"
  82.         }
  83.    
  84.     # # # # # # # # # # # # # # # # # # # # # #
  85.     # Get Wep status!
  86.     patternwep = re.compile(r'var\swepStatus="(.+)";')
  87.     swep = patternwep.search(content)
  88.     wepstat = swep.groups()[0]
  89.    
  90.     # # # # # # # # # # # # # # # # # # # # # #
  91.     # Get Auth Type!
  92.     patternauth = re.compile(r'var\sauthType="(.+)";')
  93.     authtype = patternauth.search(content).groups()[0]
  94.    
  95.    
  96.     # # # # # # # # # # # # # # # # # # # # # # # #
  97.     # ONLY WPA-PSK/WPA2 SUPPORTED.
  98.     # Did not bother with old wep since i never use it.
  99.     if authtype == "Auto" or authtype == "Open-System" or authtype == "Shared-Key" or authtype == "Open-System":
  100.         print "Wep:",wepstat,"and", authtype,"security is not supported.. change security to WPA-PSK/WPA2-PSK"
  101.         return False
  102.     # # # # # # # # # # # # # # # # # # # # # # # #
  103.    
  104.    
  105.     # # # # # # # # # # # # # # # # # # # # # #
  106.     # Get the new page content!.. WLG_wireless2.htm
  107.     #output = urllib2.urlopen(ROUTER_PAGE+"/"+wifipages[authtype])
  108.     output = urllib2.urlopen(ROUTER_PAGE+"/WLG_wireless2.htm")
  109.     content = output.read()
  110.     #print content
  111.    
  112.    
  113.     # # # # # # # # # # # # # # # # # # # # # #
  114.     # SSID.
  115.     # '<input type="text" name="ssid" value="hula" size="20" maxlength="32">'
  116.     # '<input name="ssid" value="hula" size="20" maxlength="32" type="text">'
  117.     # Content is not static and vary that why the ugly code below.
  118.    
  119.     ssid_pattern = re.compile(r'<inp.+ name="ssid".+value=(.+)>')
  120.     ssid_value = ssid_pattern.search(content).groups()[0].replace('maxlength="32"', "").replace('size="20"',"").replace('type="text"', "")
  121.     ssid_value = ssid_value[::-1][ssid_value[::-1].index('"')::]
  122.     ssid_value = ssid_value[1: len(ssid_value)-1][::-1]
  123.     print "SSID:", ssid_value
  124.    
  125.     # # # # # # # # # # # # # # # # # # # # # #
  126.     # REGION.
  127.     region_pattern = re.compile(r'<inp.+ name="tempRegion".+value="(\d+)".+')
  128.     region_value = region_pattern.search(content).groups()[0]
  129.     print "REGION:", region_value
  130.    
  131.     # # # # # # # # # # # # # # # # # # # # # #
  132.     # CHANNEL.
  133.     channel_pattern = re.compile(r'<inp.+ name="initChannel".+value="(\d+)".+')
  134.     channel_value = channel_pattern.search(content).groups()[0]
  135.     print "CHANNEL:",channel_value
  136.    
  137.     # # # # # # # # # # # # # # # # # # # # # #
  138.     # MODE.
  139.     mode_pattern = re.compile(r'<select name="opmode".+;">(.+)</select>')
  140.     modes = mode_pattern.search(content).groups()[0]
  141.     mode_option_pattern = re.compile(r'.+<option value=(.+ selected)', re.M)
  142.     mode_value = mode_option_pattern.search(modes).groups()[0].replace(" selected", "")
  143.     mode_value = mode_value[1:len(mode_value)-1]
  144.     print "MODE:",mode_value
  145.    
  146.     # post data values needed. tried to look at the source but ended up using wireshark instead.
  147.     # not tested but i belive pfChanged is set to 1 when the pwd gets changed
  148.     # so, when this is not changed we can leave the passphrase with *
  149.     values = {
  150.         "ssid" : ssid_value,
  151.         "w_channel" : channel_value,
  152.         "opmode" : mode_value,
  153.         "security_type" : authtype,
  154.         "passphrase" : "********",
  155.         "Apply" : "Apply",
  156.         "initChannel" : channel_value,
  157.         "pfChanged" : "0",
  158.         "tempSetting" : "0",
  159.         "tempRegion" : region_value
  160.     }
  161.    
  162.     data = urllib.urlencode(values)
  163.     req = urllib2.Request(url=ROUTER_PAGE+"/wireless.cgi",data=data)
  164.     content = urllib2.urlopen(req).read()
  165.     print "Sending wifi reset request..!"
  166.    
  167. def ping(ip):
  168.     '''Ping a computer using the system ping command, return True/False if got a respond.
  169.         Does retry a ping one time if it fails on the 1st attempt.
  170.     '''
  171.     retry = 0
  172.     while retry < 1:
  173.         with open(os.devnull, "wb") as void:
  174.             result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip], stdout=void, stderr=void).wait()
  175.             if result:
  176.                 if retry < 1:
  177.                     retry = 1
  178.                 else:
  179.                     return False
  180.             else:
  181.                 retry = 1
  182.                 return True
  183.  
  184. def long_wait():
  185.     print "Doing some sleep for 5 min...!"
  186.     time.sleep(60*5)
  187.     main()
  188.    
  189. def main():
  190.     '''doc'''
  191.     print "Started router monitor/resetter...!"
  192.     print "Testing Router Login."
  193.     if not router_login():
  194.         print "Login Failed"
  195.     else:
  196.         print "Login Successful."
  197.         router_getPage_WLG_wireless()
  198.    
  199.     print "Started network checking"
  200.    
  201.     ownip = get_own_lanip()
  202.     retry = 0
  203.     while 1:
  204.         try:
  205.             time.sleep(20)
  206.             iplist=[]
  207.             #ip range from n.n.n.n - n.n.n.(n+11)
  208.             # ping each client
  209.             for n in range(2,11,1):
  210.                 ip=RIP+"."+str(n)
  211.                 if ownip != ip and ROUTER_IP != ip:
  212.                     iplist.append( ping(ip) )
  213.  
  214.             #print iplist
  215.             # Reset the wifi on the router if we have less than 1 active.
  216.             # try at reset 3 time.
  217.             if iplist.count(1) < 1:
  218.                 if retry < 3:
  219.                     succsess = router_login()
  220.                     if succsess:
  221.                         router_getPage_WLG_wireless()
  222.                     else:
  223.                         print "Router Login failed"
  224.                     time.sleep(45)
  225.                     retry+=1
  226.                 else:
  227.                     long_wait()
  228.                     break
  229.             else:
  230.                 retry=0
  231.         except KeyboardInterrupt:
  232.             print "Quiting...!"
  233.             break
  234.            
  235.    
  236. if __name__ == '__main__':
  237.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement