Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
RafayGhafoor committed Sep 1, 2017
2 parents 059de32 + cf4c7af commit 87c9f29
Show file tree
Hide file tree
Showing 4 changed files with 188 additions and 93 deletions.
22 changes: 9 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ A PTCL-Router API.
- Obtain station information, showing their hostnames alongside for better readability (devices currently connected to the router).
- Obtain DHCP information.
- Block and unblock devices using their mac addresses.
- Block and unblock devices using their predefined aliases.
- Block and unblock devices using their predefined aliases.
- Reboot router.
- Over-ride hostnames associated to the mac address with custom hostnames.
- Display blocked devices.
Expand Down Expand Up @@ -44,13 +44,13 @@ optional arguments:

```python
>>> python ptcl.py
```
```

**Shows currently active devices and provides an option to block device from the display.**

```python
```python
>>> python ptcl.py -b
```
```

**Shows DHCP info for all devices connected in a day.**

Expand All @@ -72,28 +72,24 @@ optional arguments:
- [ ] Parsing router logs.
- [ ] Obtaining Pin-Code of the router and changing it.
- [ ] Displaying current password of the SSID.
- [ ] Changin router username and password from the command-line.
- [ ] Changing router username and password from the command-line.
- [ ] Changing SSID-Name.
- [ ] Adding a method to change router password.
- [ ] Option to change frequency 2.4 Ghz or 5 Ghz.
- [ ] Add CLI MODE for unblocking devices.
- [ ] Option to change frequency 2.4 Ghz or 5 Ghz.
- [ ] Option to change router transmission power.
- [ ] Improving display for blocked devices.
- [ ] Exclude android devices from station info and dhcp info.
- [ ] Exclude android devices from station info and dhcp info (Optional).
- [ ] Time restriction for user (by specifying or choosing from station info) device mac address or hostname.
- [ ] Adding URL to block unnecessary use for a website, also time limit for a site usage.
- [ ] Monitor devices connection info i.e., when they connect to the router and disconnect. Also devices uptime of the day.
- [ ] Block devices who remain connected to the router for x time (6 hours). Unblock them after 6 hours.
- [ ] Searching suspected users in the station info (Currently Active Devices) when speed is slow.
- [ ] Getting device connection info in a nice CSV file.
- [ ] Uploading CSV on a cloud everyday.
- [ ] Add CLI MODE for unblocking devices
- [ ] Uploading CSV on cloud everyday.
- [X] Setting up custom hostname for specific device (mac address).
- [X] Optimize Regular Expressions.
- [X] CLI MODE and SILENT MODE for blocking devices.
- [X] Testing on other routers from the same vendor.
- [X] Reboot router from script.
- [X] Display number of active devices.




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"]
127 changes: 85 additions & 42 deletions ptcl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,89 @@
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'

config = configobj.ConfigObj()
ptcl = Router()
# ptcl = Router(mask='192.168.10.1', password='bec10')
# 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"
# }
config[User-Aliases] = {}

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('-u', '--unblock', help="Unblock device.", nargs='?')
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('-c', '--configure', help='Configure router settings.')
parser.add_argument('-q', '--quiet', help='Quite mode.', nargs='?', default='True')
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()
# print args

if args.quiet == 'True':
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 @@ -43,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 @@ -58,56 +109,48 @@ 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
mask = raw_input("Please enter router gateway: \t\t# Default 192.168.1.1")
username = raw_input("Please enter username of your router page: \t\t# Default 'admin'")
password = raw_input("Please enter password of your router page: \t\t# Default 'admin'")
config['Router-Auth'] = {
'mask': '192.168.1.1',
'username': 'admin',
'password': 'admin'
}
with open('config.ini', 'w') as configfile:
config.write(configfile)
configure.write_config()

elif args.set_alias:
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.quiet:
elif not args.cli:
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.mac_and_host[name[dev_mac]])
ptcl.block_dev(ptcl.host_and_mac[name[dev_mac]])
print "%s has been blocked." % name[dev_mac].capitalize()


elif not args.unblock:
# print "Calling unblocker function - CLI MODE."
name = ptcl.show_active_dev()
dev_mac = int(raw_input("Please Enter Device Number: ")) - 1
ptcl.unblock_dev(ptcl.mac_and_host[name[dev_mac]])
name = show_active_dev()
ptcl.host_and_mac = dict(ptcl.host_and_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()


import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
Loading

0 comments on commit 87c9f29

Please sign in to comment.