Skip to content

Commit

Permalink
Updated
Browse files Browse the repository at this point in the history
  • Loading branch information
RafayGhafoor committed Sep 1, 2017
1 parent 80c0990 commit d72fd1c
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 69 deletions.
5 changes: 0 additions & 5 deletions config.ini

This file was deleted.

62 changes: 62 additions & 0 deletions configure.py
Original file line number Diff line number Diff line change
@@ -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"]
120 changes: 74 additions & 46 deletions ptcl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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='?')
Expand All @@ -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()])
Expand All @@ -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()])
Expand All @@ -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]])
Expand All @@ -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()


Expand Down
24 changes: 6 additions & 18 deletions router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""
Expand All @@ -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()


Expand All @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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):
Expand Down

0 comments on commit d72fd1c

Please sign in to comment.