unifi-controller-api 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 tnware
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: unifi-controller-api
3
+ Version: 0.1.0
4
+ Summary: A (read only) Python library for interacting with the Unifi Controller API
5
+ Author-email: Tyler Woods <tyler@tylermade.net>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/tnware/unifi-controller-api
8
+ Project-URL: Bug Tracker, https://github.com/tnware/unifi-controller-api/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: System :: Networking :: Monitoring
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Topic :: Utilities
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: requests
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=6.0; extra == "dev"
21
+ Requires-Dist: pytest-cov>=2.12; extra == "dev"
22
+ Requires-Dist: pytest-mock>=3.10.0; extra == "dev"
23
+ Requires-Dist: python-dotenv>=1.0.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.1.1; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # unifi-controller-api
@@ -0,0 +1 @@
1
+ # unifi-controller-api
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=42", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "unifi-controller-api"
7
+ version = "0.1.0"
8
+ description = "A (read only) Python library for interacting with the Unifi Controller API"
9
+ readme = "README.md"
10
+ authors = [
11
+ {name = "Tyler Woods", email = "tyler@tylermade.net"}
12
+ ]
13
+ license = {text = "MIT"}
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: System :: Networking :: Monitoring",
19
+ "Topic :: Software Development :: Libraries :: Python Modules",
20
+ "Topic :: Utilities"
21
+ ]
22
+ requires-python = ">=3.8"
23
+
24
+ dependencies = [
25
+ "requests",
26
+ ]
27
+
28
+ [project.urls]
29
+ "Homepage" = "https://github.com/tnware/unifi-controller-api"
30
+ "Bug Tracker" = "https://github.com/tnware/unifi-controller-api/issues"
31
+
32
+ [tool.setuptools]
33
+ packages = ["unifi_controller_api"]
34
+
35
+ [tool.setuptools.package-data]
36
+ unifi_controller_api = ["device-models.json"]
37
+
38
+ [project.optional-dependencies]
39
+ dev = [
40
+ "pytest>=6.0",
41
+ "pytest-cov>=2.12",
42
+ "pytest-mock>=3.10.0",
43
+ "python-dotenv>=1.0.0",
44
+ "ruff>=0.1.1"
45
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,32 @@
1
+ """
2
+ UniFi Controller API client for interacting with UniFi Controller API.
3
+
4
+ This package provides a Python interface to the UniFi Controller API,
5
+ allowing read-only access to sites, devices, and other network information.
6
+ """
7
+
8
+ from .api_client import UnifiController
9
+ from .models import UnifiSite, UnifiDevice, LLDPEntry
10
+ from .export import export_csv, export_json, to_dict_list
11
+ from .exceptions import (
12
+ UnifiControllerError,
13
+ UnifiAuthenticationError,
14
+ UnifiAPIError,
15
+ UnifiDataError,
16
+ UnifiModelError
17
+ )
18
+
19
+ __all__ = [
20
+ "UnifiController",
21
+ "UnifiSite",
22
+ "UnifiDevice",
23
+ "LLDPEntry",
24
+ "export_csv",
25
+ "export_json",
26
+ "to_dict_list",
27
+ "UnifiControllerError",
28
+ "UnifiAuthenticationError",
29
+ "UnifiAPIError",
30
+ "UnifiDataError",
31
+ "UnifiModelError",
32
+ ]
@@ -0,0 +1,481 @@
1
+ import json
2
+ import os
3
+
4
+ import requests
5
+ import urllib3
6
+
7
+ from typing import List, Dict, Any, Union, Optional
8
+
9
+ from .models.site import UnifiSite
10
+ from .models.device import UnifiDevice
11
+ from .logging import get_logger
12
+ from .utils import resolve_model_names, map_api_data_to_model
13
+ from .exceptions import (
14
+ UnifiAuthenticationError,
15
+ UnifiAPIError,
16
+ UnifiDataError,
17
+ UnifiModelError,
18
+ )
19
+
20
+ logger = get_logger(__name__)
21
+
22
+ DEFAULT_REPORT_FIELDS = [
23
+ "site_name",
24
+ "model",
25
+ "model_name",
26
+ "ip",
27
+ "mac",
28
+ "model_in_lts",
29
+ "model_in_eol",
30
+ "type",
31
+ "version",
32
+ "adopted",
33
+ "last_seen",
34
+ "disconnected_at",
35
+ "uptime",
36
+ "disconnection_reason",
37
+ "connect_request_ip",
38
+ ]
39
+
40
+
41
+ class UnifiController:
42
+ """
43
+ Client for interacting with the Unifi Controller API.
44
+
45
+ This class provides methods to authenticate, fetch data about sites and devices,
46
+ and generate reports from a Unifi Controller.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ controller_url,
52
+ username,
53
+ password,
54
+ is_udm_pro=False,
55
+ disable_ssl_warnings=False,
56
+ verify_ssl=True,
57
+ auto_model_mapping=True,
58
+ model_db_path=None,
59
+ ):
60
+ """
61
+ Initialize the Unifi Controller client and authenticate.
62
+
63
+ Args:
64
+ controller_url: Base URL of the Unifi Controller.
65
+ username: Username for authentication.
66
+ password: Password for authentication.
67
+ is_udm_pro: Whether the controller is a UniFi OS device. Set to True for:
68
+ UDM, UDM Pro, UDR, Cloud Key Gen2 (2.0.24+), UX, UDW,
69
+ UCG-Ultra, CK-Enterprise, and EFG. Defaults to False.
70
+ disable_ssl_warnings: Whether to disable SSL warnings when verify_ssl is False.
71
+ Defaults to False.
72
+ verify_ssl: Whether to verify SSL certificates. Can be:
73
+ - True: Verify SSL certificates (default, recommended)
74
+ - False: Disable verification (insecure, not recommended)
75
+ - str: Path to a CA bundle file or directory with certificates of trusted CAs
76
+ auto_model_mapping: Whether to automatically populate model_name using the device-models.json
77
+ database. Defaults to True.
78
+ model_db_path: Optional custom path to the device model database JSON file.
79
+ If None, uses the built-in device-models.json file. Defaults to None.
80
+ """
81
+
82
+ logger.debug(
83
+ f"Initializing UnifiController with URL: {controller_url}, is_udm_pro: {is_udm_pro}"
84
+ )
85
+ self.controller_url = controller_url
86
+ self.is_udm_pro = is_udm_pro
87
+ self.session = requests.Session()
88
+ self.verify_ssl = verify_ssl
89
+ self.auto_model_mapping = auto_model_mapping
90
+
91
+ if model_db_path is None:
92
+ self.model_db_path = os.path.join(
93
+ os.path.dirname(__file__), "device-models.json"
94
+ )
95
+ else:
96
+ self.model_db_path = model_db_path
97
+
98
+ self._device_models = None
99
+
100
+ if disable_ssl_warnings and not verify_ssl:
101
+ logger.warning(
102
+ "SSL certificate verification is disabled. This is not recommended for production use."
103
+ )
104
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
105
+ elif not verify_ssl:
106
+ logger.warning(
107
+ "SSL certificate verification is disabled but SSL warnings are enabled. You may see warning messages."
108
+ )
109
+
110
+ self.authenticate(username, password)
111
+
112
+ def authenticate(self, username, password):
113
+ """
114
+ Authenticate with the Unifi Controller.
115
+
116
+ For UniFi OS devices (UDM, UDM Pro, UDR, etc.), uses /api/auth/login
117
+ followed by changing the API path to /proxy/network. For legacy controllers,
118
+ uses /api/login directly.
119
+
120
+ Args:
121
+ username: Username for authentication. Must be a local account, not a cloud account.
122
+ password: Password for authentication.
123
+
124
+ Raises:
125
+ UnifiAuthenticationError: If authentication fails.
126
+ """
127
+ if self.is_udm_pro:
128
+ login_uri = f"{self.controller_url}/api/auth/login"
129
+ logger.debug(f"Using UDM Pro authentication endpoint: {login_uri}")
130
+ self.controller_url = f"{self.controller_url}/proxy/network"
131
+ else:
132
+ login_uri = f"{self.controller_url}/api/login"
133
+ logger.debug(f"Using legacy authentication endpoint: {login_uri}")
134
+
135
+ credentials = {"username": username, "password": "***REDACTED***"}
136
+ logger.debug(f"Attempting authentication with credentials: {credentials}")
137
+ try:
138
+ response = self.session.post(
139
+ login_uri,
140
+ json={"username": username, "password": password},
141
+ verify=self.verify_ssl,
142
+ )
143
+ response.raise_for_status()
144
+ if response.json().get("meta", {}).get("rc") == "ok":
145
+ logger.info("Successfully connected to Unifi controller.")
146
+ logger.debug("Authentication response meta: ok")
147
+ else:
148
+ error_msg = "Failed to connect: Response code not ok."
149
+ logger.warning(error_msg)
150
+ logger.debug(f"Authentication response: {response.json()}")
151
+ raise UnifiAuthenticationError(error_msg)
152
+ except requests.exceptions.RequestException as e:
153
+ error_msg = f"Authentication failed: {e}"
154
+ logger.error(error_msg)
155
+ raise UnifiAuthenticationError(error_msg) from e
156
+
157
+ def invoke_get_rest_api_call(self, url, headers=None):
158
+ """
159
+ Make a GET request to the UniFi Controller REST API.
160
+
161
+ Args:
162
+ url: The URL to send the GET request to.
163
+ headers: Optional additional headers to include in the request.
164
+
165
+ Returns:
166
+ The response object on success.
167
+
168
+ Raises:
169
+ UnifiAPIError: If the API request fails.
170
+ """
171
+ try:
172
+ if headers:
173
+ response = self.session.get(
174
+ url, headers=headers, verify=self.verify_ssl
175
+ )
176
+ else:
177
+ response = self.session.get(url, verify=self.verify_ssl)
178
+
179
+ response.raise_for_status()
180
+ logger.debug(f"API GET request to {url} successful")
181
+ return response
182
+ except requests.exceptions.RequestException as e:
183
+ error_msg = f"API GET request to {url} failed: {str(e)}"
184
+ logger.error(error_msg)
185
+ raise UnifiAPIError(error_msg) from e
186
+
187
+ def _process_api_response(
188
+ self, response: Optional[requests.Response], uri: str
189
+ ) -> List[Dict[str, Any]]:
190
+ """
191
+ Process API response and handle common error cases.
192
+
193
+ Args:
194
+ response: Response from API call
195
+ uri: URI that was called
196
+
197
+ Returns:
198
+ List of data items from the response
199
+
200
+ Raises:
201
+ UnifiAPIError: If the API request fails
202
+ UnifiDataError: If the API response cannot be parsed
203
+ """
204
+ if response is None:
205
+ raise UnifiAPIError(f"API request to {uri} failed")
206
+
207
+ try:
208
+ raw_data = response.json()
209
+ raw_results = raw_data.get("data", [])
210
+ if "data" not in raw_data:
211
+ error_msg = f"Unexpected API response format for {uri}"
212
+ logger.warning(error_msg)
213
+ raise UnifiDataError(error_msg)
214
+ return raw_results
215
+ except (ValueError, AttributeError) as e:
216
+ error_msg = f"Failed to parse API response: {e}"
217
+ logger.error(error_msg)
218
+ raise UnifiDataError(error_msg) from e
219
+
220
+ def get_unifi_site(
221
+ self, include_health, raw=False
222
+ ) -> Union[List[Dict[str, Any]], List[UnifiSite]]:
223
+ """
224
+ Get information about Unifi sites.
225
+
226
+ Args:
227
+ include_health: Whether to include health information in the response.
228
+ raw: Whether to return raw API response. Defaults to False.
229
+
230
+ Returns:
231
+ list: Site information with or without health data.
232
+ Returns a list of UnifiSite objects unless raw=True.
233
+
234
+ Raises:
235
+ UnifiAPIError: If the API request fails.
236
+ UnifiDataError: If the API response cannot be parsed.
237
+ """
238
+ uri = (
239
+ f"{self.controller_url}/api/stat/sites"
240
+ if include_health
241
+ else f"{self.controller_url}/api/self/sites"
242
+ )
243
+ response = self.invoke_get_rest_api_call(uri)
244
+ raw_results = self._process_api_response(response, uri)
245
+
246
+ if raw:
247
+ return raw_results
248
+
249
+ sites = []
250
+ for site_data in raw_results:
251
+ model_fields, extra_fields = map_api_data_to_model(site_data, UnifiSite)
252
+
253
+ site = UnifiSite(**model_fields)
254
+
255
+ if hasattr(site, "_extra_fields"):
256
+ site._extra_fields = extra_fields
257
+
258
+ sites.append(site)
259
+
260
+ return sites
261
+
262
+ def get_unifi_site_device(
263
+ self, site_name, detailed=False, mac=None, raw=False
264
+ ) -> Union[List[Dict[str, Any]], List[UnifiDevice]]:
265
+ """
266
+ Get information about devices at a specific UniFi site.
267
+
268
+ Args:
269
+ site_name: Name of the site to get devices for.
270
+ detailed: Whether to include detailed device information. Defaults to False.
271
+ mac: Optional MAC address or list of MAC addresses to filter by. Defaults to None.
272
+ raw: Whether to return raw API response. Defaults to False.
273
+
274
+ Returns:
275
+ list: Device information for the site.
276
+ Returns a list of UnifiDevice objects unless raw=True.
277
+
278
+ Raises:
279
+ UnifiAPIError: If the API request fails.
280
+ UnifiDataError: If the API response cannot be parsed.
281
+ """
282
+ if detailed:
283
+ uri = f"{self.controller_url}/api/s/{site_name}/stat/device"
284
+ else:
285
+ uri = f"{self.controller_url}/api/s/{site_name}/stat/device-basic"
286
+
287
+ if mac:
288
+ mac_list = [mac] if isinstance(mac, str) else mac
289
+ mac_list = [self.normalize_mac(m) for m in mac_list]
290
+ uri = f"{uri}?mac={','.join(mac_list)}"
291
+
292
+ response = self.invoke_get_rest_api_call(uri)
293
+ raw_results = self._process_api_response(response, uri)
294
+
295
+ if raw:
296
+ return raw_results
297
+
298
+ devices = []
299
+ for device_data in raw_results:
300
+ model_fields, extra_fields = map_api_data_to_model(device_data, UnifiDevice)
301
+
302
+ if "mac" not in model_fields and "mac" in device_data:
303
+ model_fields["mac"] = device_data["mac"]
304
+
305
+ device = UnifiDevice(**model_fields)
306
+
307
+ device._extra_fields = extra_fields
308
+
309
+ device.site_name = site_name
310
+
311
+ devices.append(device)
312
+
313
+ if self.auto_model_mapping and devices:
314
+ resolve_model_names(devices, self.model_db_path)
315
+
316
+ return devices
317
+
318
+ def normalize_mac(self, mac_address):
319
+ """
320
+ Normalize MAC address to colon-separated format.
321
+
322
+ Args:
323
+ mac_address: MAC address string in any format (with or without separators).
324
+
325
+ Returns:
326
+ str: MAC address with colons between each pair of characters.
327
+ """
328
+ mac_clean = (
329
+ mac_address.replace(":", "").replace("-", "").replace(".", "").lower()
330
+ )
331
+
332
+ return ":".join(mac_clean[i : i + 2] for i in range(0, len(mac_clean), 2))
333
+
334
+ def load_device_models(self, force_reload=False):
335
+ """
336
+ Load the device models database from a JSON file.
337
+
338
+ Args:
339
+ force_reload: Whether to force reload the device models database.
340
+ Defaults to False.
341
+
342
+ Returns:
343
+ dict: The device models database.
344
+
345
+ Raises:
346
+ UnifiModelError: If the device models database cannot be loaded.
347
+ """
348
+ if self._device_models is not None and not force_reload:
349
+ return self._device_models
350
+
351
+ logger.debug(f"Loading device models from {self.model_db_path}")
352
+ try:
353
+ with open(self.model_db_path, "r", encoding="utf-8") as f:
354
+ self._device_models = json.load(f)
355
+ return self._device_models
356
+ except (json.JSONDecodeError, IOError) as e:
357
+ error_msg = f"Failed to load device models from {self.model_db_path}: {e}"
358
+ logger.error(error_msg)
359
+ raise UnifiModelError(error_msg) from e
360
+
361
+ def generate_device_report(
362
+ self, sites, output_csv_path, device_models_json_path=None, fields=None
363
+ ):
364
+ """
365
+ Generate a CSV report of devices across multiple sites.
366
+
367
+ Args:
368
+ sites: List of sites to include in the report.
369
+ output_csv_path: Path where the CSV report will be saved.
370
+ device_models_json_path: Path to the JSON file with device model information.
371
+ If None, uses the default path. Defaults to None.
372
+ fields: List of fields to include in the report. If None, uses DEFAULT_REPORT_FIELDS.
373
+ Defaults to None.
374
+
375
+ Raises:
376
+ UnifiAPIError: If the API request to site devices fails.
377
+ UnifiDataError: If the site devices data cannot be parsed.
378
+ UnifiModelError: If the device models cannot be loaded.
379
+ """
380
+ devices = self.devices_report(sites, device_models_json_path)
381
+
382
+ if not devices:
383
+ logger.info("No device data found across any sites. Creating empty CSV.")
384
+ with open(output_csv_path, "w", newline="", encoding="utf-8") as csvfile:
385
+ csvfile.write("")
386
+ return
387
+
388
+ if fields is None:
389
+ fields = DEFAULT_REPORT_FIELDS
390
+
391
+ report_data = []
392
+
393
+ for device in devices:
394
+ device_dict = {}
395
+
396
+ for field in fields:
397
+ attr_name = field
398
+
399
+ if attr_name == "site_name" and (
400
+ not hasattr(device, attr_name) or getattr(device, attr_name) is None
401
+ ):
402
+ device_dict[field] = "Unknown Site"
403
+ elif hasattr(device, attr_name):
404
+ device_dict[field] = getattr(device, attr_name)
405
+ else:
406
+ device_dict[field] = None
407
+
408
+ report_data.append(device_dict)
409
+
410
+ from .export import export_csv
411
+
412
+ export_csv(report_data, output_csv_path)
413
+
414
+ def devices_report(
415
+ self,
416
+ sites: Union[List[UnifiSite], List[Dict[str, Any]]],
417
+ device_models_json_path=None,
418
+ ) -> List[UnifiDevice]:
419
+ """
420
+ Generate a detailed device report across multiple sites.
421
+
422
+ This method provides comprehensive information about all devices across the specified sites.
423
+
424
+ Args:
425
+ sites: List of sites to include in the report. Can be UnifiSite objects or raw dicts.
426
+ device_models_json_path: Path to the JSON file with device model information.
427
+ If None, uses the default path. Defaults to None.
428
+
429
+ Returns:
430
+ list: A list of UnifiDevice objects with enhanced model information.
431
+
432
+ Raises:
433
+ UnifiAPIError: If the API request to site devices fails.
434
+ UnifiDataError: If the site devices data cannot be parsed.
435
+ UnifiModelError: If the device models cannot be loaded.
436
+ """
437
+ if device_models_json_path is None:
438
+ device_models_json_path = self.model_db_path
439
+
440
+ report_data: List[UnifiDevice] = []
441
+
442
+ for site in sites:
443
+ if isinstance(site, UnifiSite):
444
+ site_name = site.desc or "Unknown Site"
445
+ site_id = site.name
446
+ else:
447
+ site_name = site.get("desc", "Unknown Site")
448
+ site_id = site.get("name")
449
+
450
+ try:
451
+ devices = self.get_unifi_site_device(site_name=site_id, detailed=True)
452
+
453
+ for device in devices:
454
+ if isinstance(device, UnifiDevice) and not device.unifi_id:
455
+ device.unifi_id = site_id
456
+
457
+ if not isinstance(devices, list):
458
+ logger.warning(
459
+ f"Expected list of devices for site {site_name}, got {type(devices)}"
460
+ )
461
+ continue
462
+
463
+ valid_devices = [d for d in devices if isinstance(d, UnifiDevice)]
464
+ if len(valid_devices) != len(devices):
465
+ logger.warning(
466
+ f"Some devices for site {site_name} were not UnifiDevice objects"
467
+ )
468
+ report_data.extend(valid_devices)
469
+
470
+ except (UnifiAPIError, UnifiDataError) as e:
471
+ logger.error(f"Error getting devices for site {site_name}: {e}")
472
+
473
+ if report_data and self.auto_model_mapping:
474
+ try:
475
+ resolve_model_names(report_data, device_models_json_path)
476
+ except Exception as e:
477
+ error_msg = f"Error resolving model names: {e}"
478
+ logger.error(error_msg)
479
+ raise UnifiModelError(error_msg) from e
480
+
481
+ return report_data