Exemple #1
0
    def probe(self):
        c = Controller(self._ctrl_addr,
                       self._ctrl_user,
                       self._ctrl_passwd,
                       ssl_verify=False)
        for ap in c.get_aps():
            if ap.get('name') == self._hostname:
                if self._metric == Metrics.STATUS:
                    return [nagiosplugin.Metric('status', self._get_state(ap), context='null')]
                elif self._metric == Metrics.CPU:
                    return [nagiosplugin.Metric('cpu', self._get_cpu(ap), context='cpu')]
                elif self._metric == Metrics.MEMORY:
                    return [nagiosplugin.Metric('memory', self._get_mem(ap), context='memory')]
                elif self._metric == Metrics.SPEED:
                    return [nagiosplugin.Metric('speed', self._get_speed(ap), context='speed')]
                elif self._metric == Metrics.SATISFACTION:
                    return [nagiosplugin.Metric('satisfaction', self._get_satisfaction(ap), context='satisfaction')]
                elif self._metric == Metrics.TEMPERATURE:
                    return [nagiosplugin.Metric('temperature', self._get_temperature(ap), context='temperature')]
                elif self._metric == Metrics.OVERHEATING:
                    return [nagiosplugin.Metric('overheating', self._get_overheating(ap), context='null')]
                elif self._metric == Metrics.POWER_LEVEL:
                    return [nagiosplugin.Metric('power_level', self._get_power_level(ap), context='power_level')]

        raise nagiosplugin.CheckError('unable to find specified device: {}'.format(self._hostname))
Exemple #2
0
 def __init__(self) -> None:
     self._controller = Controller(
         config.unifi.host,
         config.unifi.username,
         config.unifi.password,
         port=config.unifi.port,
         site_id=config.unifi.site_id,
         ssl_verify=True,
     )
     self._clients: Dict[str, Any] = {}
     self._usergroups: Dict[str, _UserGroup] = {}
Exemple #3
0
def getLAN():
    c = Controller('192.168.1.44',
                   'twistedfields',
                   config.PASSWORD,
                   ssl_verify=False)
    lan = {}
    aps = c.get_aps()
    for ap in aps:
        try:
            name = ap.get('name')
        except:
            name = 'no name'
        ip = ap['ip']
        lan['AP ' + name] = ip
    return lan
Exemple #4
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Unifi Controller."""
    from pyunifi.controller import Controller, APIError

    host = config.get(CONF_HOST)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    site_id = config.get(CONF_SITE_ID)
    port = config.get(CONF_PORT)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    mac = config.get(CONF_MAC)
    device_name = config.get(CONF_NAME)

    try:
        ctrl = Controller(host,
                          username,
                          password,
                          port,
                          version='v4',
                          site_id=site_id,
                          ssl_verify=verify_ssl)
    except APIError as ex:
        _LOGGER.error("Failed to connect to Unifi: %s", ex)
        hass.components.persistent_notification.create(
            'Failed to connect to Unifi. '
            'Error: {}<br />'
            'You will need to restart hass after fixing.'
            ''.format(ex),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)
        return False

    add_entities([UnifiController(ctrl, mac, device_name)])
Exemple #5
0
def modify_unifi(macs, action):
    c = Controller(unifi_controller_url, unifi_username, unifi_password, port=unifi_port)
    wlans = c.get_wlan_conf()
    for wlan in wlans:
        if wlan["name"] == wlan_name and wlan["_id"] == wlan_id:
            macFilterList = wlan["mac_filter_list"]
            for mac in macs:
                if (action == add):
                    if mac not in macFilterList:
                        macFilterList.append(mac.upper())
                elif (action == remove):
                    if mac in macFilterList:
                        macFilterList.remove(mac.upper())
            newSetting = {"mac_filter_list": macFilterList}
            c._api_update("rest/wlanconf/{0}".format(wlan_id), newSetting)
            break
Exemple #6
0
def get_scanner(hass, config):
    """Set up the Unifi device_tracker."""
    from pyunifi.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)
    verify_ssl = config[DOMAIN].get(CONF_VERIFY_SSL)

    persistent_notification = loader.get_component('persistent_notification')
    try:
        ctrl = Controller(host,
                          username,
                          password,
                          port,
                          version='v4',
                          site_id=site_id,
                          ssl_verify=verify_ssl)
    except urllib.error.HTTPError as ex:
        _LOGGER.error("Failed to connect to Unifi: %s", ex)
        persistent_notification.create(
            hass,
            'Failed to connect to Unifi. '
            'Error: {}<br />'
            'You will need to restart hass after fixing.'
            ''.format(ex),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)
        return False

    return UnifiScanner(ctrl)
Exemple #7
0
def get_scanner(hass, config):
    """Set up the Unifi device_tracker."""
    from pyunifi.controller import Controller, APIError

    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)
    verify_ssl = config[DOMAIN].get(CONF_VERIFY_SSL)
    detection_time = config[DOMAIN].get(CONF_DETECTION_TIME)
    monitored_conditions = config[DOMAIN].get(CONF_MONITORED_CONDITIONS)
    ssid_filter = config[DOMAIN].get(CONF_SSID_FILTER)

    try:
        ctrl = Controller(host,
                          username,
                          password,
                          port,
                          version='v4',
                          site_id=site_id,
                          ssl_verify=verify_ssl)
    except APIError as ex:
        _LOGGER.error("Failed to connect to Unifi: %s", ex)
        hass.components.persistent_notification.create(
            'Failed to connect to Unifi. '
            'Error: {}<br />'
            'You will need to restart hass after fixing.'
            ''.format(ex),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)
        return False

    return UnifiScanner(ctrl, detection_time, ssid_filter,
                        monitored_conditions)
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Unifi sensor."""
    from pyunifi.controller import Controller, APIError

    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    site_id = config.get(CONF_SITE_ID)
    version = config.get(CONF_UNIFI_VERSION)
    port = config.get(CONF_PORT)
    verify_ssl = config.get(CONF_VERIFY_SSL)

    try:
        ctrl = Controller(host,
                          username,
                          password,
                          port,
                          version,
                          site_id=site_id,
                          ssl_verify=verify_ssl)
    except APIError as ex:
        _LOGGER.error("Failed to connect to Unifi Security Gateway: %s", ex)
        return False

    for sensor in config.get(CONF_MONITORED_CONDITIONS):
        add_entities([UnifiGatewaySensor(hass, ctrl, name, sensor)], True)
Exemple #9
0
def get_scanner():
    """Set up the Unifi device_tracker."""
    from pyunifi.controller import Controller

    ctrl = Controller(os.environ.get('UNIFI_HOST', DEFAULT_HOST),
                      os.environ['UNIFI_USERNAME'],
                      os.environ['UNIFI_PASSWORD'],
                      os.environ.get('UNIFI_PORT', DEFAULT_PORT),
                      version='v4',
                      site_id=os.environ.get('UNIFI_SITE_ID', "default"),
                      ssl_verify=DEFAULT_VERIFY_SSL)

    if os.environ.get('DETECTION_TIME', None) is None:
        detection_time = DEFAULT_DETECTION_TIME
    else:
        detection_time = int(os.environ['DETECTION_TIME'])

    return UnifiScanner(ctrl, timedelta(seconds=detection_time))
    if userName is None:
        userName = raw_input('Username: '******'Password: '******'ip', 'Unknown')
    hostname = client.get('hostname')
    name = client.get('name', hostname)
    if not args.mixedcase:
def setup_platform(hass, config, add_devices, discovery_info=None):
    """begin using the pyunifi import """
    from pyunifi.controller import Controller, APIError
    """get all the parameters passed by the user to access the controller"""
    host = config.get(CONF_HOST)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    site_id = config.get(CONF_SITE_ID)
    port = config.get(CONF_PORT)
    user_group_name = config.get(CONF_USER_GROUP_NAME)
    """verify ssl isn't functioning, I've bypassed it for the moment"""
    verify_ssl = False
    """config.get(CONF_VERIFY_SSL)"""
    try:
        ctrl = Controller(host,
                          username,
                          password,
                          port,
                          version='v4',
                          site_id=site_id,
                          ssl_verify=verify_ssl)
    except APIError as ex:
        _LOGGER.error("Failed to connect to Unifi: %s", ex)
        hass.components.persistent_notification.create(
            'Failed to connect to Unifi. '
            'Error: {}<br />'
            'You will need to restart hass after fixing.'
            ''.format(ex),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)
        return False
    # the controller was loaded properly now get the user groups to find the one you want
    user_group_found = False
    user_group_id = 0
    # Loop through all of the User Groups looking for the one specified
    for user_group in ctrl.get_user_groups():
        if 'name' in user_group:
            if user_group['name'] == user_group_name:
                # The user group was found store it
                user_group_found = True
                user_group_id = user_group['_id']
    # if user group was not found return false give error message
    if not user_group_found:
        _LOGGER.error("Failed to find Unifi userGroup with name of: %s",
                      user_group_name)
        hass.components.persistent_notification.create(
            'Failed to find Unifi User Group '
            'Name: {}<br />'
            'You will need to restart hass after fixing.'
            ''.format(user_group_name),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)
        return False

    # define an array for storing the HASS devices, each Hass Device will be a Unifi User
    devices = []
    # Get all users in group requested (in Unifi users are all known devices regardless of connection status, clients
    # are connected users)

    for user in ctrl.get_users():
        if 'usergroup_id' in user:
            if user['usergroup_id'] == user_group_id:
                # we have found a user that we should add
                if 'name' in user:
                    hostname = user['name']
                else:
                    hostname = 'no name'
                if 'blocked' in user:
                    not_blocked = not bool(user['blocked'])
                else:
                    not_blocked = True
                # LOGGER.error('blocked from user ' + str(tempb) + ' from conversion: ' + str(not_blocked))
                mac_address = user['mac']
                devices.append(
                    UnifiClientSwitch(hostname, mac_address, not_blocked, ctrl,
                                      60, 60))
                continue
    # All the users been appended to device array
    add_devices(devices)
Exemple #12
0
    print("unknown action argument, " + sys.argv[1] +
          "; must be block or unblock")

input_file = open('config.json')
j = json.load(input_file)

controllerAddress = j["controller"]
controllerUser = j["user"]
controllerPassword = j["password"]

#print (j)

ctrl = Controller(controllerAddress,
                  controllerUser,
                  controllerPassword,
                  8443,
                  version='v4',
                  site_id="default",
                  ssl_verify=False)

for client in j["clients"]:
    mac = client['mac']
    device = client['device']

    if action == "block":
        print("Blocking : %s : %s" % (device, mac))
        ctrl.block_client(mac)

    if action == "unblock":
        print("Unblocking : %s : %s" % (device, mac))
        ctrl.unblock_client(mac)
Exemple #13
0
class UnifiApi:
    def __init__(self) -> None:
        self._controller = Controller(
            config.unifi.host,
            config.unifi.username,
            config.unifi.password,
            port=config.unifi.port,
            site_id=config.unifi.site_id,
            ssl_verify=True,
        )
        self._clients: Dict[str, Any] = {}
        self._usergroups: Dict[str, _UserGroup] = {}

    def update(self) -> None:
        self._update_user_groups()
        self._update_clients()
        self._update_last_active()

    def _update_user_groups(self) -> None:
        _logger.debug("Getting UNIFI user groups")
        for group in self._controller.get_user_groups():
            id = str(group["_id"])
            name = str(group["name"])

            # Create new
            if id not in self._usergroups:
                self._usergroups[id] = _UserGroup(id, name)
            # Update existing
            else:
                self._usergroups[id].name = name

    def _update_clients(self) -> None:
        _logger.debug("Getting UNIFI clients")
        for client in self._controller.get_clients():
            # logger.debug("Client info: " + str(client))
            self._clients[client["mac"]] = client

    def _update_last_active(self) -> None:
        _logger.debug("Updating last active time")
        for client in self._clients.values():
            if "usergroup_id" in client:
                group_id = client["usergroup_id"]
            else:
                group_id = self._get_default_group().id

            group = self._usergroups[group_id]
            group.was_home = group.is_home
            group.last_active_time = time()

        # Log if Home/Away was changed
        for group in self._usergroups.values():
            group.was_home = group.is_home
            group.is_home = UnifiApi._calculate_is_home(group)

            if group.was_home != group.is_home:
                state_msg = "home" if group.is_home else "away"
                _logger.info(f"Usergroup {group.name} is {state_msg}")

    def _get_default_group(self) -> _UserGroup:
        for group in self._usergroups.values():
            if group.name == GuestOf.both.value:
                return group
        raise Exception("No default usergroup found")

    def get_client(self, mac_address: str) -> Union[Any, None]:
        """Tries to find the client with the specified mac address. Returns None if it hasn't been active yet"""
        if mac_address in self._clients:
            return self._clients[mac_address]

    def is_guest_active(self, *guest_of_list: GuestOf) -> bool:
        """Checks if a guest is active on the network

        Args:
            guest_of_list (GuestOf): the guest group to check. If empty, it will check all guest groups.
        """
        if len(guest_of_list) == 0:
            return self._is_any_guest_active()

        for guest_of in guest_of_list:
            usergroup = self._get_user_group(guest_of)
            if usergroup and usergroup.is_home:
                return True

        return False

    def _is_any_guest_active(self) -> bool:
        for guest_of in GuestOf:
            active = self.is_guest_active(guest_of)
            if active:
                return True
        return False

    def _get_user_group(self, friend_of: GuestOf) -> Union[_UserGroup, None]:
        for usergroup in self._usergroups.values():
            if usergroup.name == friend_of.value:
                return usergroup

    @staticmethod
    def _calculate_is_home(usergroup: _UserGroup) -> bool:
        now = time()
        elapsed_time = now - usergroup.last_active_time
        return elapsed_time <= config.unifi.guest_inactive_time
Exemple #14
0
import urllib.request

macs = ["04:d6:aa:0f:e8:e9"]
offline_delay = 600
last_online_time = time.time()
online = True
url = "http://192.168.13.25/json.htm?type=command&param=switchlight&idx=393&switchcmd="
online_url = url + "Off"
offline_url = url + "On"

from pyunifi.controller import Controller

c = Controller("wifi.kantoor2.datux.nl",
               "admin",
               "kutje123",
               8443,
               "v5",
               "default",
               ssl_verify=False)

while True:
    # get aps and client list
    aps = c.get_aps()
    ap_names = dict([(ap['mac'], ap.get('name')) for ap in aps])
    clients = c.get_clients()
    clients.sort(key=lambda x: -x['rssi'])

    FORMAT = '%-16s  %18s  %-12s  %4s  %4s  %3s  %3s %s'
    print()
    print(FORMAT % ('NAME', 'MAC', 'AP', 'CHAN', 'RSSI', 'RX', 'TX', 'online'))
Exemple #15
0
import os
from pyunifi.controller import Controller

c = Controller('192.168.1.44', 'twistedfields', '=9M8R+M7i',ssl_verify=False)
for ap in c.get_aps():
    print('AP named %s with MAC %s' % (ap.get('name'), ap['ip']))


#os.system('curl 'https://192.168.1.44:8443/api/login' --data-binary '{"username":"******","password":"******","strict":true}' --compressed --insecure -c cookies.txt')

#os.system("curl 'https://192.168.1.44:8443/api/s/default/stat/device' --insecure -b cookies.txt -c cookies.txt | python -m json.tool > output.json")


import json



with open("output.json",'r') as f:
        jlines = json.load(f)

ips = list(map(lambda x: x['ip'], jlines['data']))
names = list(map(lambda x: x['name'], jlines['data']))
 

print(ips)
print(names)
Exemple #16
0
password = os.getenv("UNIFI_API_PASSWORD")
site_id = os.getenv("UNIFI_API_SITEID", "default")
ssl_verify = os.path.join(os.getenv("CERTDIR"), os.getenv("CERTNAME"))


def sizeof_fmt(num, suffix="B"):
    for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, "Y", suffix)


controller = Controller(host="localhost",
                        port=8443,
                        username=username,
                        password=password,
                        site_id=site_id,
                        ssl_verify=ssl_verify)

ap_clients = {}

for client in controller.get_clients():
    ap_mac = client["ap_mac"]

    if ap_mac not in ap_clients:
        ap_clients[ap_mac] = []

    ap_clients[ap_mac].append(client)

for ap in controller.get_aps():
    try:
Exemple #17
0
def connect_controller():
    with open('/data/options.json', "r") as read_file:
        data = json.load(read_file)

    return Controller(data["ControllerURL"], data["Login"]["Username"], data["Login"]["Password"],data["Port"],data["Version"],data["SiteID"],data["ValidSSL"])
Exemple #18
0
#!/usr/bin/env python3
import time
import urllib.request

macs=[ "04:d6:aa:0f:e8:e9" ]
offline_delay=600
last_online_time=time.time()
online=True
url="http://192.168.13.25/json.htm?type=command&param=switchlight&idx=393&switchcmd="
online_url =url+"Off"
offline_url=url+"On"

from pyunifi.controller import Controller


c = Controller("wifi.kantoor2.datux.nl", "admin", "kutje123", 8443, "v5" , "default", ssl_verify=False)



while True:
    # get aps and client list
    aps = c.get_aps()
    ap_names = dict([(ap['mac'], ap.get('name')) for ap in aps])
    clients = c.get_clients()
    clients.sort(key=lambda x: -x['rssi'])


    FORMAT = '%-16s  %18s  %-12s  %4s  %4s  %3s  %3s %s'
    print()
    print(FORMAT % ('NAME', 'MAC', 'AP', 'CHAN', 'RSSI', 'RX', 'TX', 'online'))