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)
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
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)
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)
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)
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
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 +
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'))
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())
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']
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
#!/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.