From d72fd1c3e316e1c79256e683cabf8e2dab62c17d Mon Sep 17 00:00:00 2001 From: Rafay Ghafoor Date: Fri, 1 Sep 2017 23:22:25 +0500 Subject: [PATCH] Updated --- config.ini | 5 --- configure.py | 62 ++++++++++++++++++++++++++ ptcl.py | 120 +++++++++++++++++++++++++++++++-------------------- router.py | 24 +++-------- 4 files changed, 142 insertions(+), 69 deletions(-) delete mode 100644 config.ini create mode 100644 configure.py diff --git a/config.ini b/config.ini deleted file mode 100644 index c32d5d0..0000000 --- a/config.ini +++ /dev/null @@ -1,5 +0,0 @@ -[User-Aliases] -[Router-Auth] -username = admin -password = bec10 -mask = 192.168.1.10 diff --git a/configure.py b/configure.py new file mode 100644 index 0000000..60b00b3 --- /dev/null +++ b/configure.py @@ -0,0 +1,62 @@ +import configobj +import os + + +def write_config(): + # Creating a config file + try: + os.chdir(os.path.expanduser(os.path.join('~', ''))) + os.makedirs('.config' + os.sep + "ptcl") + os.chdir('.config' + os.sep + "ptcl") + + except OSError: + # If already exists + pass + + config = configobj.ConfigObj() + DEFAULT = {'mask': '192.168.1.1', 'username': 'admin', 'password': 'admin'} + mask = raw_input("Leave empty for default configuration.\nPlease enter router gateway\t(Default 192.168.1.1)\t: ") + + if mask: + DEFAULT['mask'] = mask + username = raw_input("Please enter router username\t(Default admin)\t: ") + + if username: + DEFAULT['username'] = username + password = raw_input("Please enter router password\t(Default admin)\t: ") + + if password: + DEFAULT['password'] = password + config['Router-Auth'] = DEFAULT + config['Aliases'] = {} + + with open('config.ini', 'w') as configfile: + config.write(configfile) + print '\nConfiguration file Generated.' + + +def set_alias(): + # Defining custom aliases + config = configobj.ConfigObj('config.ini') + + while True: + hostname = raw_input("Set Alias for hosname: ") + if hostname == 'q': + break + macaddress= raw_input("Enter it\'s macaddress: ") + + if macaddress == 'q': + break + + else: + if hostname not in config["Aliases"]: + config["Aliases"][hostname] = macaddress + with open('config.ini', 'r+') as configfile: + config.write(configfile) + else: + print "Already Present." + +def get_alias(): + # Return Aliases + config = configobj.ConfigObj('config.ini') + return config["Aliases"] diff --git a/ptcl.py b/ptcl.py index e0f8ec7..1ac0b2c 100755 --- a/ptcl.py +++ b/ptcl.py @@ -2,24 +2,69 @@ import argparse import sys import configobj +import configure +import os +from tabulate import tabulate + +path = os.path.expanduser(os.path.join('~', '.config' + os.sep + 'ptcl')) + +if os.path.exists(path): + os.chdir(path) + config = configobj.ConfigObj('config.ini') + ptcl = Router(mask=config["Router-Auth"]["mask"], password=config["Router-Auth"]["password"]) + +else: + print "Configuration file doesn't exists. Run it with --configure parameter.\nExecuting Fallback mode." + ptcl = Router(mask="192.168.10.1", password="123motorcross") + # ptcl = Router(password='ptcl') + + +def show_dhcpinfo(): + ''' + Shows DHCP information. + ''' + ptcl.get_dhcpinfo() + print tabulate({"HOSTNAME": ptcl.dev_hostname, "MAC-ADDRESSES": ptcl.mac_address}, headers=['HOSTNAME', 'MAC-ADDRESSES'], tablefmt='fancy_grid') + print "\n\n\t\tTotal Devices Connected Today are: [%s].\n\n" % len(ptcl.dev_hostname) + + +def show_active_dev(): + ''' + Shows active devices (Mac Addresses) and their hostnames. + ''' + ptcl.get_stationinfo() + ptcl.get_dhcpinfo() + ptcl.host_and_mac = tuple(zip(ptcl.dev_hostname, ptcl.mac_address)) + hostnames = [] + display_list = [] + aliases = configure.get_alias() + count = 1 + print "\nShowing Currently Active Devices.\n" + for hostname, mac in ptcl.host_and_mac: + for active_clients in ptcl.active_dev: + if active_clients in mac: + if mac in aliases.itervalues(): + display_list.append([count, aliases.keys()[aliases.values().index(mac)], active_clients]) + else: + display_list.append([count, hostname, active_clients]) + hostnames.append(hostname) + count += 1 + print tabulate(display_list, headers=["DEVICE-NO.", "HOSTNAME", "MAC"], tablefmt="fancy_grid") + return hostnames + + +def show_blocked_dev(): + ''' + Display blocked devices. + ''' + r, soup = ptcl.scrape_page(ptcl.mask + "wlmacflt.cmd?action=view") + print "Showing blocked devices.\n" + for i in soup.findAll('td'): + if not i.find("input"): + if Router.mac_adr_regex.search(i.text): + print i.text + '\n' -# ptcl = Router(password='ptcl') -my_macs = {"mytab": "5c:2e:59:4d:33:67", -"ahmer": "68:94:23:AC:59:51", -"asad": "A0:32:99:AB:33:31", -"hhp": "44-1C-A8-73-A3-17", -"haris": "64:5A:04:76:C7:9C" -} -ptcl = Router(mask='192.168.10.1', password='123motorcross') -# Defining custom aliases -# config['User-Aliases'] = { -# "mytab": "5c:2e:59:4d:33:67", -# "ahmer": "68:94:23:AC:59:51", -# "asad": "A0:32:99:AB:33:31", -# "hhp": "44-1C-A8-73-A3-17" -# } - def main(): parser = argparse.ArgumentParser(description="Control PTCL router from command-line.") parser.add_argument('-b', '--block', help="Block device.", nargs='?') @@ -36,9 +81,10 @@ def main(): # print args if args.cli == 'False': + my_macs = configure.get_alias() if args.block: # print "Calling blocker Function" - ptcl.get_sessionkey() + ptcl.key() if args.block in my_macs.iterkeys(): # print "Calling blocker function - AUTOMATED MODE." ptcl.block_dev(my_macs[args.block.lower()]) @@ -49,7 +95,6 @@ def main(): print "User not found." elif args.unblock: - ptcl.get_sessionkey() if args.unblock in my_macs.iterkeys(): # print "Calling unblocker function - AUTOMATED MODE" ptcl.unblock_dev(my_macs[args.unblock.lower()]) @@ -64,52 +109,34 @@ def main(): elif args.restart: # print "Calling restart Function" - ptcl.get_sessionkey() ptcl.reboot_router() elif args.show_dhcp: # print "Calling DHCP_info Function" - # ptcl.get_sessionkey() - ptcl.show_dhcpinfo() + show_dhcpinfo() elif args.blocked_dev: - ptcl.show_blocked_dev() + show_blocked_dev() elif args.configure: - # Creating a config file - config = configobj.ConfigObj() - config['User-Aliases'] = {} - DEFAULT = {'mask': '192.168.1.1', 'username': 'admin', 'password': 'admin'} - mask = raw_input("Leave empty for default configuration.\nPlease enter router gateway\t(Default 192.168.1.1)\t: ") - if mask: - DEFAULT['mask'] = mask - username = raw_input("Please enter router username\t(Default admin)\t: ") - if username: - DEFAULT['username'] = username - password = raw_input("Please enter router password\t(Default admin)\t: ") - if password: - DEFAULT['password'] = password - config['Router-Auth'] = DEFAULT - with open('config.ini', 'w') as configfile: - config.write(configfile) - print '\nConfiguration file Generated.' + configure.write_config() elif args.set_alias: - pass + show_active_dev() + configure.set_alias() elif args.show_active == '.': # print "Calling show_active Function" - ptcl.show_active_dev() + show_active_dev() else: print "Invalid Argument" elif not args.cli: - ptcl.get_sessionkey() if not args.block: # print "Calling blocker function - CLI MODE." - name = ptcl.show_active_dev() + name = show_active_dev() ptcl.host_and_mac = dict(ptcl.host_and_mac) dev_mac = int(raw_input("Please Enter Device Number: ")) - 1 ptcl.block_dev(ptcl.host_and_mac[name[dev_mac]]) @@ -118,10 +145,11 @@ def main(): elif not args.unblock: # print "Calling unblocker function - CLI MODE." - name = ptcl.show_active_dev() + name = show_active_dev() ptcl.host_and_mac = dict(ptcl.host_and_mac) - dev_mac = int(raw_input("Please Enter Device Number: ")) - 1 - ptcl.unblock_dev(ptcl.host_and_mac[name[dev_mac]]) + dev_mac = raw_input("Please enter device mac address: ") + ptcl.unblock_dev(dev_mac) + # ptcl.unblock_dev(ptcl.host_and_mac[name[dev_mac]]) print "%s has been unblocked." % name[dev_mac].capitalize() diff --git a/router.py b/router.py index 4042cfc..01bd65f 100755 --- a/router.py +++ b/router.py @@ -29,7 +29,7 @@ def __init__(self, mask="192.168.1.1", username="admin", password="admin"): self.dev_hostname = [] # Devices Hostname self.mac_address = [] # Devices Mac Address self.active_dev = [] # Active Devices on Wi-Fi - self.host_and_mac = {} # Mac Addresses and Hostnames + self.host_and_mac = [] # Mac Addresses and Hostnames self.session = requests.Session() self.session.auth = (self.username, self.password) self.session_key = "" @@ -46,7 +46,7 @@ def scrape_page(self, url): html_soup = bs4.BeautifulSoup(request_url.content, 'html.parser') return request_url, html_soup except requests.exceptions.ConnectionError: - print "Internet Connection Down.\nExiting..." + print("Internet Connection Down.\nExiting...") sys.exit() @@ -55,7 +55,8 @@ def get_sessionkey(self): Gets session key from the html page. ''' r, soup = self.scrape_page(self.mask + "wlmacflt.cmd") - self.session_key= re.search(r'\d{3,30}', r.content).group().encode('ascii') + self.session_key = re.search(r'\d{3,30}', r.content).group().encode('ascii') + return self.session_key def get_dhcpinfo(self): @@ -108,6 +109,7 @@ def show_active_dev(self): hostnames = [] display_list = [] count = 1 + print "\nShowing Currently Active Devices.\n" for hostname, mac in self.host_and_mac: for active_clients in self.active_dev: if active_clients in mac: @@ -144,26 +146,12 @@ def show_blocked_dev(self): print i.text + '\n' - def set_hostname(self, custom_name, mac_address): - ''' - Set custom hostname for a device. For example: - >>> DESKTOP-1RXG23 --> My-PC - ''' - self.get_dhcpinfo() - custom_hostnames = {} - self.host_and_mac = dict(zip(self.dev_hostname, self.mac_address)) - for i in self.host_and_mac.items(): - if mac_address in i: - del(self.host_and_mac[i[0]]) - self.host_and_mac[custom_name] = mac_address - - def reboot_router(self): ''' Reboots Router. ''' r, soup = self.scrape_page(self.mask + ("rebootinfo.cgi?sessionKey=%s") % self.session_key) - print "Rebooted." + print "Router has been succesfully rebooted." def time_restriction(self):