From 81e08ea29de7ad685b47af93f258f6174bfe2ed9 Mon Sep 17 00:00:00 2001 From: Rafay Ghafoor Date: Fri, 29 Sep 2017 22:53:35 +0500 Subject: [PATCH] methods name shortened, python 3 port --- configure.py | 4 +- ptcl.py | 258 +++++++++++++++++++++++++-------------------------- router.py | 42 ++++----- 3 files changed, 151 insertions(+), 153 deletions(-) diff --git a/configure.py b/configure.py index ffea993..28c8be8 100644 --- a/configure.py +++ b/configure.py @@ -33,7 +33,7 @@ def write_config(): with open('config.ini', 'w') as configfile: config.write(configfile) - print '\nConfiguration file Generated.' + print('\nConfiguration file Generated.') def set_alias(): @@ -55,7 +55,7 @@ def set_alias(): with open('config.ini', 'r+') as configfile: config.write(configfile) else: - print "Already Present." + print("Already Present.") def get_alias(): diff --git a/ptcl.py b/ptcl.py index 23d209a..d9e2595 100755 --- a/ptcl.py +++ b/ptcl.py @@ -6,136 +6,136 @@ import os from tabulate import tabulate - +ptcl = Router(password='123motorcross') def show_dhcpinfo(): ''' Shows DHCP information. ''' - ptcl.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.stationinfo() - ptcl.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 tabulate([[i.text]], headers=["BLOCKED-DEV"], tablefmt="fancy_grid") - - -def main(): - parser = argparse.ArgumentParser(description="Control PTCL router from command-line.") - parser.add_argument('-b', '--block', help="Block device.", nargs='?') - parser.add_argument('-sb', '--blocked_dev', help='Display blocked devices.', action='store_true') - parser.add_argument('-ub', '--unblock', help="Unblock device.", nargs='?') - parser.add_argument('-a', '--active-devices', help="Gets number of devices connected to the router.", action='store_true') - parser.add_argument('-r', '--restart', help="Restart Router.", action='store_true') - parser.add_argument('-sd', '--show-dhcp', help='Show DHCP Info.', action='store_true') - parser.add_argument('-s', '--show-active', help='Show Active Devices.', default='.') - parser.add_argument('--configure', help='Configure router settings.', action='store_true') - parser.add_argument('-sa', '--set-alias', help='Set custom alias for a device hostname.', action='store_true') - parser.add_argument('-c', '--cli', help='Silent mode.', nargs='?', default='False') - args = parser.parse_args() - - if configure.config_check() == True: - if configure.config: - global ptcl - ptcl = Router(mask=configure.config["Router-Auth"]["mask"], password=configure.config["Router-Auth"]["password"]) - - else: - configure.config_check() - sys.exit("Please Re-run.") - - my_macs = configure.get_alias() - - if args.block: - if args.block == '1': - 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]]) - print "%s has been blocked." % name[dev_mac].capitalize() - - elif args.block != '1' and args.block in my_macs.iterkeys(): - # print "Calling blocker function - AUTOMATED MODE." - ptcl.block_dev(my_macs[args.block.lower()]) - print "%s has been blocked." % args.block.capitalize() - if args.block not in my_macs.iterkeys(): - print "User not found." - - elif args.block != '1' and args.block not in my_macs.iterkeys(): - print "User not found." - - elif args.unblock: - if args.unblock == '1': - show_blocked_dev() - dev_mac = raw_input("Please enter device mac address: ") - ptcl.unblock_dev(dev_mac) - print "%s has been unblocked." % dev_mac - - elif args.unblock != 1 and args.unblock in my_macs.iterkeys(): - # print "Calling unblocker function - AUTOMATED MODE" - ptcl.unblock_dev(my_macs[args.unblock.lower()]) - print "%s has been unblocked." % args.unblock.capitalize() - - elif args.unblock != 1 and args.unblock not in my_macs.iterkeys(): - print "User not found." - - elif args.active_devices: - # print "Calling Station info Function" - ptcl.stationinfo() - print "Currently active devices are:", len(ptcl.active_dev) - - elif args.restart: - # print "Calling restart Function" - ptcl.reboot() - - elif args.show_dhcp: - # print "Calling DHCP_info Function" - show_dhcpinfo() - - elif args.blocked_dev: - show_blocked_dev() - - elif args.set_alias: - show_active_dev() - configure.set_alias() - - elif args.show_active == '.': - # print "Calling show_active Function" - show_active_dev() - - else: - print "Invalid Argument" - -main() + # print(ptcl.dhcpinfo()) + print(tabulate([ptcl.dhcpinfo()], headers=['HOSTNAME'], tablefmt='fancy_grid')) + +show_dhcpinfo() + +# def show_active_dev(): +# ''' +# Shows active devices (Mac Addresses) and their hostnames. +# ''' +# ptcl.stationinfo() +# ptcl.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(tabulate([[i.text]], headers=["BLOCKED-DEV"], tablefmt="fancy_grid")) +# +# +# def main(): +# parser = argparse.ArgumentParser(description="Control PTCL router from command-line.") +# parser.add_argument('-b', '--block', help="Block device.", nargs='?') +# parser.add_argument('-sb', '--blocked_dev', help='Display blocked devices.', action='store_true') +# parser.add_argument('-ub', '--unblock', help="Unblock device.", nargs='?') +# parser.add_argument('-a', '--active-devices', help="Gets number of devices connected to the router.", action='store_true') +# parser.add_argument('-r', '--restart', help="Restart Router.", action='store_true') +# parser.add_argument('-sd', '--show-dhcp', help='Show DHCP Info.', action='store_true') +# parser.add_argument('-s', '--show-active', help='Show Active Devices.', default='.') +# parser.add_argument('--configure', help='Configure router settings.', action='store_true') +# parser.add_argument('-sa', '--set-alias', help='Set custom alias for a device hostname.', action='store_true') +# parser.add_argument('-c', '--cli', help='Silent mode.', nargs='?', default='False') +# args = parser.parse_args() +# +# if configure.config_check() == True: +# if configure.config: +# global ptcl +# ptcl = Router(mask=configure.config["Router-Auth"]["mask"], password=configure.config["Router-Auth"]["password"]) +# +# else: +# configure.config_check() +# sys.exit("Please Re-run.") +# +# my_macs = configure.get_alias() +# +# if args.block: +# if args.block == '1': +# 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]]) +# print("%s has been blocked." % name[dev_mac].capitalize()) +# +# elif args.block != '1' and args.block in my_macs.iterkeys(): +# # print "Calling blocker function - AUTOMATED MODE." +# ptcl.block_dev(my_macs[args.block.lower()]) +# print("%s has been blocked." % args.block.capitalize()) +# if args.block not in my_macs.iterkeys(): +# print("User not found.") +# +# elif args.block != '1' and args.block not in my_macs.iterkeys(): +# print("User not found.") +# +# elif args.unblock: +# if args.unblock == '1': +# show_blocked_dev() +# dev_mac = raw_input("Please enter device mac address: ") +# ptcl.unblock_dev(dev_mac) +# print("%s has been unblocked." % dev_mac) +# +# elif args.unblock != 1 and args.unblock in my_macs.iterkeys(): +# # print( "Calling unblocker function - AUTOMATED MODE") +# ptcl.unblock_dev(my_macs[args.unblock.lower()]) +# print("%s has been unblocked." % args.unblock.capitalize()) +# +# elif args.unblock != 1 and args.unblock not in my_macs.iterkeys(): +# print("User not found.") +# +# elif args.active_devices: +# # print( "Calling Station info Function") +# ptcl.stationinfo() +# print("Currently active devices are:", len(ptcl.active_dev)) +# +# elif args.restart: +# # print( "Calling restart Function") +# ptcl.reboot() +# +# elif args.show_dhcp: +# # print( "Calling DHCP_info Function") +# show_dhcpinfo() +# +# elif args.blocked_dev: +# show_blocked_dev() +# +# elif args.set_alias: +# show_active_dev() +# configure.set_alias() +# +# elif args.show_active == '.': +# # print "Calling show_active Function" +# show_active_dev() +# +# else: +# print("Invalid Argument") +# +# main() diff --git a/router.py b/router.py index da8a60f..a94f186 100755 --- a/router.py +++ b/router.py @@ -21,7 +21,7 @@ class Router(object): mac_adr_regex = re.compile(r'^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$') - def __init__(self, mask="192.168.1.1", username="admin", password="admin"): + def __init__(self, mask="192.168.10.1", username="admin", password="admin"): self.mask = "http://" + mask + '/' self.username = username self.password = password @@ -33,7 +33,7 @@ def __init__(self, mask="192.168.1.1", username="admin", password="admin"): self.sessionKey = "" - def scrape_page(self, url): + def scrape_page(self, url, create_soup='n'): ''' Scrape given link and create a beautiful soup object. ''' @@ -42,8 +42,10 @@ def scrape_page(self, url): if request_url.status_code == 401: sys.exit("Username or Password is incorrect.") elif request_url.status_code == 200: - html_soup = bs4.BeautifulSoup(request_url.content, 'lxml') - return request_url, html_soup + if create_soup == 'y': + html_soup = bs4.BeautifulSoup(request_url.content, 'lxml') + return html_soup + return request_url except requests.exceptions.ConnectionError: print("Internet Connection Down.\nExiting...") sys.exit() @@ -53,7 +55,7 @@ def session_key(self): ''' Gets session key from the html page. ''' - r, soup = self.scrape_page(self.mask + "wlmacflt.cmd") + r = self.scrape_page(url=self.mask + "wlmacflt.cmd") self.sessionKey = re.search(r'\d{3,30}', r.content).group().encode('ascii') return self.sessionKey @@ -62,7 +64,7 @@ def dhcpinfo(self): ''' Gets information from dhcp i.e., Mac Adresses and Hostnames. ''' - + soup = self.scrape_page(url=self.mask + "dhcpinfo.html", create_soup='y') td = soup.findAll('td') for i in td: if self.mac_adr_regex.search(i.text): @@ -87,36 +89,39 @@ def stationinfo(self): ''' Gets information about the connected devices. ''' - r, soup = self.scrape_page(self.mask + "wlstationlist.cmd") + soup = self.scrape_page(url=self.mask + "wlstationlist.cmd", create_soup='y') for i in soup.findAll('td'): if self.mac_adr_regex.search(i.text.strip()): self.active_dev.append(i.text.strip().lower().encode('ascii')) return self.active_dev - def block_dev(self, devmac): + def block(self, devmac): ''' Block device using Mac Address. ''' - r, soup = self.scrape_page(self.mask + "wlmacflt.cmd?action=add&wlFltMacAddr=%s&sessionKey=%s" % (devmac, self.session_key())) + requests.get(self.mask + "wlmacflt.cmd?action=add&wlFltMacAddr=%s&sessionKey=%s" % (devmac, self.session_key())) - def unblock_dev(self, udevmac): + def unblock(self, udevmac): ''' Unblock device using Mac Address. ''' - r, soup = self.scrape_page(self.mask + "wlmacflt.cmd?action=remove&rmLst=%s&sessionKey=%s" % (udevmac, self.session_key())) + requests.get(self.mask + "wlmacflt.cmd?action=remove&rmLst=%s&sessionKey=%s" % (udevmac, self.session_key())) def reboot(self): ''' Reboots Router. ''' - r, soup = self.scrape_page(self.mask + "rebootinfo.cgi?sessionKey=%s" % self.session_key()) - print "Router has been succesfully rebooted." + r = requests.get(self.mask + "rebootinfo.cgi?sessionKey=%s" % self.session_key()) + if r.status_code == 200: + print("Router has been succesfully rebooted.") + else: + print("Request not successful.") - def time_restriction(self): + def time_limit(self): ''' Restricts user from using internet for limited time. ''' @@ -130,14 +135,7 @@ def url_filter(self): pass - def url_remove_filter(self): - ''' - Removes url filter after specified time or when provided. - ''' - pass - - - def change_passwd(self): + def passwd(self): ''' Change the password of the router. '''