Beispiel #1
0
def temp_authorize_guest(track_id):
    '''Function for giving temporary internet access for a client
    
       This function send API commands to controller, return ok
    '''
    guest_track = Guesttrack.query.filter_by(track_id=track_id).first()
    if not guest_track:
        current_app.logger.error("Called temp_authorize_guest with wrong track ID:%s"%track_id)
        abort(404)
        
    #validate session associated with this track ID
    guest_session = Guestsession.query.filter_by(id=guest_track.session_id).first()
    if not guest_session:
        current_app.logger.error("Called temp_authorize_guest with wrong Session from track ID:%s"%track_id)
        abort(404)   
    guest_track.state =GUESTRACK_TEMP_AUTH
    db.session.commit()

    #get details from track ID and authorize
    if not current_app.config['NO_UNIFI'] :
        try:
            c =  Controller(current_app.config['LANDINGSITE']['unifihost'], current_app.config['LANDINGSITE']['unifiadmin'], current_app.config['LANDINGSITE']['unifipass'],current_app.config['LANDINGSITE']['unifiport'],current_app.config['LANDINGSITE']['unifiversion'],current_app.config['LANDINGSITE']['unifisiteid'])       
            c.authorize_guest(guest_track.device_mac,5,ap_mac=guest_track.ap_mac)    
        except:
            current_app.logger.exception('Exception occured while trying to authorize User')
            return jsonify({'status':0,'msg': "Error!!"})
        return jsonify({'status':1,'msg': "DONE"})
    else:
        return jsonify({'status':1,'msg': "DEBUG enabled"})
    def run(self):

        hosts = defaultdict()

        ipl_begin = ip2long(self.ip_begin)
        ipl_end = ip2long(self.ip_end)

        try:
            c = Controller(self.controller, self.username, self.password)

            for client in c.get_clients():

                ip = client.get('ip', False)
                if not ip:
                    continue

                ipl_cur = ip2long(ip)
                if ipl_cur >= ipl_begin and ipl_cur <= ipl_end:
                    hosts[ip] = client['mac'].lower()

            self.hosts = hosts

        except:
            # somethimes a weird SSL Handshake errors appears in combination
            # with the ubiquiti tomcat server.
            #
            # see: http://stackoverflow.com/questions/14167508/intermittent-sslv3-alert-handshake-failure-under-python
            return False
Beispiel #3
0
def get_scanner(hass, config):
    """Setup Unifi device_tracker."""
    from unifi.controller import Controller

    if not validate_config(config, {DOMAIN: [CONF_USERNAME, CONF_PASSWORD]},
                           _LOGGER):
        _LOGGER.error('Invalid configuration')
        return False

    this_config = config[DOMAIN]
    host = this_config.get(CONF_HOST, 'localhost')
    username = this_config.get(CONF_USERNAME)
    password = this_config.get(CONF_PASSWORD)

    try:
        port = int(this_config.get(CONF_PORT, 8443))
    except ValueError:
        _LOGGER.error('Invalid port (must be numeric like 8443)')
        return False

    try:
        ctrl = Controller(host, username, password, port, 'v4')
    except urllib.error.HTTPError as ex:
        _LOGGER.error('Failed to connect to unifi: %s', ex)
        return False

    return UnifiScanner(ctrl)
Beispiel #4
0
def authorize_guest(track_id):
    '''Function called after respective auth mechanisms are completed
    
       This function send API commands to controller, redirect user to correct URL
    '''
    
    #
    #Validate track id and get all the needed variables
    guest_track = Guesttrack.query.filter_by(track_id=track_id).first()
    if not guest_track:
        current_app.logger.error("Called authorize_guest with wrong track ID:%s"%track_id)
        abort(404)
        
    #validate session associated with this track ID
    guest_session = Guestsession.query.filter_by(id=guest_track.session_id).first()
    if not guest_session:
        current_app.logger.error("Called authorize_guest with wrong Session from track ID:%s"%track_id)
        abort(404)   


    #Check if the session is authorized
    if not guest_session.state == SESSION_AUTHORIZED:
        current_app.logger.error("Called authorize_guest with wrong Non Authorized session with track ID:%s"%track_id)
        abort(404) 

    #Send  unifi API commands if the user has completed login
    if not current_app.config['NO_UNIFI'] :
        #code to send auth command to controller
        try:
            c =  Controller(current_app.config['LANDINGSITE']['unifihost'], current_app.config['LANDINGSITE']['unifiadmin'], current_app.config['LANDINGSITE']['unifipass'],current_app.config['LANDINGSITE']['unifiport'],current_app.config['LANDINGSITE']['unifiversion'],current_app.config['LANDINGSITE']['unifisiteid'])       
            c.authorize_guest(guest_track.device_mac,guest_session.duration,ap_mac=guest_track.ap_mac)    
        except:
            current_app.logger.exception('Exception occured while trying to authorize User')
            return "Error Occured!"
    
    #Code to handle guest after successful login 
    
    if current_app.config['LANDINGSITE']['redirecturl']:
        return redirect(format_url(current_app.config['LANDINGSITE']['redirecturl']))
    elif guest_track.orig_url is not None:
        #redirect User's URL
        return redirect(format_url(guest_track.orig_url))
    else:
        #redirect user to google.com
        return redirect(format_url("www.google.com"),code=302)
Beispiel #5
0
    def __init__(self, host, user, pwd, port="8443", ver="v4"):
        """
        Initialize the Unifi API, binding to the controller on the specified
        host/port with the passed password and setting up the appropriate
        internal connection.

        @param host Host to connect to.
        @param user User to connect as, needs to be at least a R/O admin.
        @param pwd Password of the user to connect as.
        @param port Port that the Unifi API is listening on.
        @param ver Version of the Unifi API to use, default to v4.
        """

        # Create controller instance.
        self._controller = Controller(host, user, pwd, port, ver)
        self._owner = user
        self._stats = []
Beispiel #6
0
def get_scanner(hass, config):
    """Setup Unifi device_tracker."""
    from unifi.controller import Controller

    host = config[DOMAIN].get(CONF_HOST)
    username = config[DOMAIN].get(CONF_USERNAME)
    password = config[DOMAIN].get(CONF_PASSWORD)
    site_id = config[DOMAIN].get(CONF_SITE_ID)
    port = config[DOMAIN].get(CONF_PORT)

    try:
        ctrl = Controller(host, username, password, port, 'v4', site_id)
    except urllib.error.HTTPError as ex:
        _LOGGER.error('Failed to connect to unifi: %s', ex)
        return False

    return UnifiScanner(ctrl)
Beispiel #7
0
    required=True)
parser.add_argument('-a',
                    '--apiversion',
                    help='Base version of the AP (v2 or v3)',
                    required=False,
                    default='v2')
parser.add_argument('-s',
                    '--site',
                    help='For --apiversion v3 only, chosee site name',
                    required=False,
                    default='default')

args = parser.parse_args()

site_ctrl_version = args.targetversion
c = Controller(args.controller, args.user, args.password, args.apiversion,
               args.site)

command_list = open('command_list.sh', 'w+')

updated = 0
needs_update = 0

for ap in c.get_aps():

    if ap['version'] == site_ctrl_version:
        updated = updated + 1

    else:
        needs_update = needs_update + 1

        command_list.write('sshpass -p ' + args.password +
Beispiel #8
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'))
import argparse
import json

from unifi.controller import Controller

parser = argparse.ArgumentParser()
parser.add_argument('-c', '--controller', default='unifi', help='the controller address (default "unifi")')
parser.add_argument('-u', '--username', default='admin', help='the controller username (default("admin")')
parser.add_argument('-p', '--password', default='', help='the controller password')
parser.add_argument('-b', '--port', default='8443', help='the controller port (default "8443")')
parser.add_argument('-v', '--version', default='v2', help='the controller base version (default "v2")')
parser.add_argument('-s', '--siteid', default='default', help='the site ID, UniFi >=3.x only (default "default")')
args = parser.parse_args()

c = Controller(args.controller, args.username, args.password, args.version, args.siteid)

aps = c.get_aps()
total = guests = users = rx = tx = 0
data = dict(all=1)

for ap in aps:
    data[ap['name']] = dict(uptime=ap['uptime'], total=ap['num_sta'], guests=ap['guest-num_sta'], users=ap['user-num_sta'],
                            tx=ap['stat']['tx_bytes'], rx=ap['stat']['rx_bytes'])
    total += ap['num_sta']
    guests += ap['guest-num_sta']
    users += ap['user-num_sta']
    rx += ap['stat']['rx_bytes']
    tx += ap['stat']['tx_bytes']

data["all"] = dict( total=total, guests=guests, users=users, rx=rx, tx=tx )
Beispiel #10
0
    except:
        return 0

def set_timestamp(timestamp):
    with open (args.timestamp, 'w') as file:
        file.write('%s\n' % str(timestamp))

def unixtimestamp_to_datetime(timestamp):
    mytime = datetime.datetime.fromtimestamp(timestamp/1000)
    mytime.replace(microsecond = (timestamp % 1000) * 1000)
    return mytime


try:
    chost = args.controller
    c = Controller(chost, args.user, args.password)
except Exception:
    logdata = "%s %s Connection error to host = %s, error = %s" % (time.strftime("%b %d %H:%M:%S"), chost, chost, sys.exc_info()[1])
    write_to_logfile(logdata)
    sys.exit()

try:
    aps = c.get_aps()
except Exception:
    logdata = "%s %s Connection error to host = %s, error = %s" % (time.strftime("%b %d %H:%M:%S"), chost, chost, sys.exc_info()[1])
    write_to_logfile(logdata)
    sys.exit()

users = c.get_users()
clients = c.get_clients()
storedtimestamp = unixtimestamp_to_datetime(get_last_timestamp())
Beispiel #11
0
    userName = args.user
else:
    userName = os.getenv("UNIFI_USER")
    if userName is None:
        userName = raw_input('Username: '******'Password: '******'ip', 'Unknown')
    hostname = client.get('hostname')
    name = client.get('name', hostname)
    if not args.mixedcase:
        name = name.lower()
    mac = client['mac']
import argparse
from unifi.controller import Controller

parser = argparse.ArgumentParser(description='Create SSH update script for syswrapper.sh based firmware mass-upgrade, requires OpenSSH and sshpass to work.')
parser.add_argument('-c', '--controller', help='Controller DNS name or IP, this cannot be localhost here.', required=True)
parser.add_argument('-u', '--user', help='Site admin username.', required=True)
parser.add_argument('-p', '--password', help='Site admin password.', required=True)
parser.add_argument('-t', '--targetversion', help='Target firmware version. Look up precise versioning in the Ubiquiti KB, also see /usr/lib/unifi/dl/firmware/', required=True)
parser.add_argument('-a', '--apiversion', help='Base version of the AP (v2 or v3)', required=False, default='v2')
parser.add_argument('-s', '--site', help='For --apiversion v3 only, chosee site name', required=False, default='default')

args = parser.parse_args()

site_ctrl_version = args.targetversion
c = Controller(args.controller, args.user, args.password, args.apiversion, args.site)

command_list = open('command_list.sh', 'w+')

updated = 0
needs_update = 0

for ap in c.get_aps():

    if ap['version'] == site_ctrl_version:
        updated = updated + 1

    else:
        needs_update = needs_update+1

        command_list.write('sshpass -p '
Beispiel #13
0
 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
Beispiel #14
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
Beispiel #15
0
#!/usr/bin/python
from unifi.controller import Controller
import subprocess

###############################
#Change me here for where to send email and what controller to connect to

recipient = '*****@*****.**'
subject = 'Address blocked on Unifi Controller'

c = Controller('127.0.0.1', '<username>', '<password>', '<port>', '<version>')

###############################
################################
#Define the empty variable
body="The following addresses were blocked because they were not on the allowed list:"

def send_message(recipient, subject, body):
    try:
      process = subprocess.Popen(['mail', '-s', subject, recipient],
                               stdin=subprocess.PIPE)
    except Exception, error:
      print error
    process.communicate(body)


#Create the empty list that will be used for our connected clients
connectedlist = list()
allowed = list()

#Create a list of the current mac addresses.
        putval(identifier('tx_performance'), values('tx_dropped', 'tx_retries', 'tx_packets') )

        # Clients associated with ESSID on this AP
        putval(identifier('ath_nodes'), values('num_sta'))

        # Miscellaneous statistics
        prefixes = ['ath_stat-', '']
        bases = ['ccq', 'rx_frags', 'rx_nwids', 'rx_crypts']
        for type, key in [ [p + b for p in prefixes] for b in bases]:
            putval(identifier(type), values(key) )

if __name__ == '__main__':
    from urllib2 import URLError, HTTPError

    while True:
        now = datetime.datetime.utcnow()

        try:
            if not controller: 
                controller = Controller(args.controller, args.username, args.password, args.port, args.version, args.site_id)
#                controller = Controller(**args)
            for ap in controller.get_aps():
                print_controller_stats(controller)
                print_ap_stats(ap)
                print_essid_stats(ap)

            time.sleep(args.interval)            
        except (URLError, HTTPError) as err:
            controller = None
            time.sleep(10)
            continue
Beispiel #17
0
import argparse
from unifi.controller import Controller

c = Controller('X.X.X.X', 'admin', 'PASSWORD', '8443', 'v3', 'emartinez')
aps = c.get_aps()
ap_names = dict([(ap['mac'], ap['name']) for ap in aps])
clients = c.get_clients()
clients.sort(key=lambda x: -x['rssi'])
print(clients)

c = Controller('Y.Y.Y.Y', 'admin', 'PASSWORD', '8443', 'v3',
               'em-oficinas-centrales')
aps = c.get_aps()
ap_names = dict([(ap['mac'], ap['name']) for ap in aps])
clients = c.get_clients()
clients.sort(key=lambda x: -x['rssi'])
print(clients)
Beispiel #18
0
class Unifi:
    """
    Helper class which collects node information from a Unifi controller instance
    that delivers networks. This polls the complete AP info using get_aps() with
    the Python bindings for the Unifi JSON API, and reformats the output to fit
    in the standard Alfred format.
    """

    # Initialization
    # --------------

    def __init__(self, host, user, pwd, port="8443", ver="v4"):
        """
        Initialize the Unifi API, binding to the controller on the specified
        host/port with the passed password and setting up the appropriate
        internal connection.

        @param host Host to connect to.
        @param user User to connect as, needs to be at least a R/O admin.
        @param pwd Password of the user to connect as.
        @param port Port that the Unifi API is listening on.
        @param ver Version of the Unifi API to use, default to v4.
        """

        # Create controller instance.
        self._controller = Controller(host, user, pwd, port, ver)
        self._owner = user
        self._stats = []

    def nodeinfo(self, gw):
        """
        Collect node information of the nodes connected to the Unifi
        controller, returning the information in a format suitable to
        later processing in a decoded form.

        @param gw Gateway to use for Unifi controller.
        @return nodeinfo structure as returned by Batman.
        """

        # Walk the nodes.
        nodes = []
        for node in self._controller.get_aps():
            if "uptime" not in node:
                continue

            # Create nodes.
            nodeid = sub("[^a-fA-F0-9]+", "", node["mac"])
            nodes.append(
                {
                    "hardware": {"model": "Unifi {0}".format(MODELS.get(node["model"], "unknown")), "nproc": 1},
                    "hostname": "freifunk-celle-unifi-{0}".format(nodeid),
                    "location": {"latitude": node["x"], "longitude": node["y"]},
                    "network": {"addresses": [node["ip"]], "mac": node["mac"]},
                    "node_id": nodeid,
                    "owner": {"contact": "*****@*****.**"},
                    "software": {
                        "autoupdater": {"branch": "stable", "enabled": True},
                        "firmware": {"base": "Unifi", "release": node["version"]},
                    },
                    "system": {"site_code": "ffce"},
                }
            )

            # Create stats.
            self._stats.append(
                {
                    "clients": {"total": -1, "wifi": -1},
                    "node_id": nodeid,
                    "gateway": gw,
                    "uptime": node["uptime"],
                    "traffic": {
                        "rx": {"bytes": node["stat"].get("rx_bytes", 0), "packets": node["stat"].get("rx_packets", 0)},
                        "tx": {"bytes": node["stat"].get("tx_bytes", 0), "packets": node["stat"].get("tx_bytes", 0)},
                    },
                }
            )

        # Return node list.
        return nodes

    def statistics(self):
        """
        Fetch the precollected statistics that were derived from the
        Unifi API statistics data. This must be called after the node
        info has already been retrieved.

        @return Statistics data.
        """

        # Return stats.
        return self._stats