Ejemplo n.º 1
0
class MyCtlr:
    ###############################################################
    ## CONTROLLER PARAMETERS                                     ##
    ###############################################################
    ctlr_ip = ""
    ctlr_username = ""
    ctlr_password = ""
    ctlr_url = ""
    debug = 0

    ###############################################################
    ## Initialization                                            ##
    ###############################################################
    def __init__(self, ip, ctlr_web_id, ctlr_web_pw, ctrl_web_port, ctrl_web_version):
        self.ctlr_ip = ip
        self.ctlr_username = ctlr_web_id
        self.ctlr_password = ctlr_web_pw
        self.ctrl_web_port = ctrl_web_port
        self.ctrl_web_version = ctrl_web_version

    ###############################################################
    ## CONTROLLER FUNCTIONS                                      ##
    ###############################################################
    def make_datastr(self, ll):
        dstr = ""
        for couple in ll:
            dstr = dstr + str(couple[0]) + "=" + str(couple[1]) + "&"
        return dstr[:-1]

    def make_jsonstr(self, ll):
        jstr = ""
        for couple in ll:
            jstr = jstr + "\"" + str(couple[0]) + "\":" + couple[1] + ","
        return "{" + jstr[:-1] + "}"

    def decode_json(self, jstr):
        decoded = json.loads(jstr)
        return json.loads(json.dumps(decoded["data"]))

    def ctlr_login(self):
        self.c = Controller(self.ctlr_ip,self.ctlr_username,self.ctlr_password,self.ctrl_web_port,self.ctrl_web_version)
        return self.c

    def ctrl_stat_user_blocked(self):
        users = self.c.get_users()
	blocked = []
        for user in users:
             if user.has_key('blocked'):
                  if str(user['blocked']) == 'True':
                       blocked.append(user)
        return blocked

    def ctrl_list_group_members(self,group_id):
        users = self.c.get_users()
	group_users = []
        for user in users:
             if user.has_key('usergroup_id'):
                  if str(user['usergroup_id']) == group_id:
                       group_users.append(user)
        return group_users

    def ctrl_list_essid_members(self,essid_id):
        users = self.c.get_clients()
	group_users = []
        for user in users:
             if user.has_key('essid'):
                  if str(user['essid']) == essid_id:
                       group_users.append(user)
        return group_users

    def ctrl_list_group(self):
        grouplist={}
        grouplist = self.c.get_user_groups()
        return grouplist

    def ctlr_stat_device(self):
        aps = self.c.get_aps()
        return aps

    def ctlr_stat_sta(self):
        clients = self.c.get_clients()
        return clients

    def ctlr_wlan_conf(self):
        wlan_conf = self.c.get_wlan_conf()
        return wlan_conf

    def ctlr_reboot_ap(self, apnamefilter=""):
        aplist = self.ctlr_stat_device()
        try:
            for ap in aplist:
                if not ap.has_key('state') or ap['state'] != 1:
                    continue
                if (ap.has_key('name') and ap['name'].startswith(apnamefilter)) or not ap.has_key('name'):
                    if ap.has_key('name'): print "Rebooting AP:", ap['name']
                    if not ap.has_key('name'): print "Rebooting AP:", ap['mac']
                    self.c.restart_ap(ap['mac'])
        except ValueError:
            pass        

    def ctlr_enabled_wlans_on_all_ap(self, apnamefilter="", target_wlan=[], en=True, wlans_forced_off=[]):
        aplist = self.ctlr_stat_device()
        wlanlist = self.ctlr_wlan_conf()
        if self.debug>0: print "Configure all Wireless LANs status to", en
        try:
            for ap in self.aplist:
                if not ap.has_key('state') or ap['state'] != 1:
                    continue
                if ap.has_key('name') and ap['name'].startswith(apnamefilter):
                    self.ctlr_enabled_wlans(ap['name'], target_wlan, en, aplist, wlanlist, wlans_forced_off)
                elif not ap.has_key('name'):
                    self.ctlr_enabled_wlans(ap['mac'], target_wlan, en, aplist, wlanlist, wlans_forced_off)
        except ValueError:
            pass

    def ctlr_mac_cmd(self, target_mac, command):
        if command == "block":
            self.c.block_client(target_mac)
        elif command == "unblock":
            self.c.unblock_client(target_mac)
        elif command == "reconnect":
            self.c.disconnect_client(target_mac)
        elif command == "restart":
            self.c.restart_ap(target_mac)
        return True

    def ctlr_get_ap_stat_field(self, apname, tag, aplist=""):
        if aplist=="":
            aplist = self.ctlr_stat_device()
        try:
            for ap in self.aplist:
                if ap.has_key('name') and apname == ap['name']:
                    return ap[tag]
        except ValueError:
            pass

    # pass a list of tags
    def ctlr_get_sta_stat_fields_by_mac(self, stamac, tag, stalist=""):
        if stalist=="":
            stalist = self.ctlr_stat_sta()
        try:
            for sta in stalist:
                if sta.has_key('mac') and stamac == sta['mac']:
                    rtag = []
                    for t in tag:
                        rtag.append(sta[t])
                    return rtag
        except ValueError:
            pass

    def ctlr_get_all_sta_mac(self, stalist=""):
        sta_mac_list = []
        if stalist=="":
            stalist = self.ctlr_stat_sta()
        try:
            for sta in stalist:
                if sta.has_key('mac'):
                    sta_mac_list.append(sta['mac'])
        except ValueError:
            pass
        return sta_mac_list

    def ctlr_get_sta_stat_fields_by_name(self, name, tag, stalist=""):
        if stalist=="":
            stalist = self.ctlr_stat_sta()
        try:
            for sta in self.stalist:
                if sta.has_key('hostname') and name == sta['hostname']:
                    rtag = []
                    for t in tag:
                        rtag.append(sta[t])
                    return rtag
        except ValueError:
            pass
Ejemplo n.º 2
0
def handle(msg):

	chat_id = '******USERID-CHAT-TELEGRAM********'
	command = msg['text']
	c = Controller('IP-UBIQUITI-CONTROLLER', 'USER-UBIQUITI-CONTROLLER', 'PASS-UBIQUITI-CONTROLLER', 'PORT-UBIQUITI', 'VERSION-UBIQUITI-CONTROLLER')	 

	if command == '/news':

		d = feedparser.parse(host_feed)
		for i in range(5):
			teste = d.entries[i].title +" : " +d.entries[i].link
			bot.sendMessage(chat_id, teste)

	elif command == '/speedtest':

		servers = []
		st = speedtest.Speedtest()
		st.get_servers(servers)
		st.get_best_server()
		download = st.download()/1000000
		upload = st.upload()/1000000
		bot.sendMessage(chat_id, "Download: " + str(download) + " Mbit/s \n" + "Upload: " + str(upload) + " Mbit/s")

	elif command == '/aps':

		for ap in c.get_aps():
			bot.sendMessage(chat_id, 'AP named %s with MAC %s' % (ap.get('name'), ap['mac']))


	elif command == '/clients':

		count = 0
		for client in c.get_clients():
			count = count + 1

		bot.sendMessage(chat_id, "We have " + str(count) + " users online!")

	elif command == '/list':

		for client in c.get_clients():

			name = client.get('hostname') or client.get('ip', 'Unknown')
			mac = client['mac']

			bot.sendMessage(chat_id, name + " " + mac)

	elif "/block" in command:

		mac_block = command[7:]
		c.block_client(mac_block)
		bot.sendMessage(chat_id, "User successfully blocked!")

	elif "/unblock" in command:

		mac_unblock = command[9:]
		c.unblock_client(mac_unblock)
		bot.sendMessage(chat_id, "User successfully unblocked!")

	elif command == "/alerts":
		count_alerts = 0
		for event in c.get_events():
			count_alerts = count_alerts + 1
			if count_alerts == 11:
				break
			else:
                bot.sendMessage(chat_id, event.get('msg'))
Ejemplo n.º 3
0
#Print a list of the known mac addresses.
print "The connected addresses to the AP are the following:"
for conn in connectedlist: print conn

print "The allowed mac addresses are as follows:"
for a in allowed: print a

#Compare the list of addresses from what is connected vs what is allowed.
s = set(allowed)
blockme = [x for x in connectedlist if x not in s]

if not blockme:
    print "All addresses matched the allowed list.  There are no addresses to block."
    print "Goodbye."
else:
    print "I am going to block the following addresses."
    for b in blockme: print b
    #Run through the list and block all the addresses that didn't match the allowed mac addresses.
    for mac in blockme:
        #Command to block an address.
        #DEBUG BLOCK HERE
    c.block_client(mac)
        #
    print "Block complete for the following address:"
        print mac
    body += "\n"
    body += mac
    send_message(recipient, subject, body)
    print("Email sent of blocked addresses")