Python-Unifi-Client 1.3.2__py3-none-any.whl → 1.3.4__py3-none-any.whl
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.
- python_unifi_client/client.py +591 -569
- {python_unifi_client-1.3.2.dist-info → python_unifi_client-1.3.4.dist-info}/METADATA +1 -1
- python_unifi_client-1.3.4.dist-info/RECORD +6 -0
- python_unifi_client-1.3.2.dist-info/RECORD +0 -6
- {python_unifi_client-1.3.2.dist-info → python_unifi_client-1.3.4.dist-info}/WHEEL +0 -0
- {python_unifi_client-1.3.2.dist-info → python_unifi_client-1.3.4.dist-info}/top_level.txt +0 -0
python_unifi_client/client.py
CHANGED
|
@@ -10,39 +10,72 @@ import http.client as http_client
|
|
|
10
10
|
import logging
|
|
11
11
|
import base64
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
13
|
+
_logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# ── Exception hierarchy ───────────────────────────────────────────
|
|
17
|
+
#
|
|
18
|
+
# New code should catch these base types. The legacy names below
|
|
19
|
+
# inherit from them, so `except UnifiAuthError` catches both
|
|
20
|
+
# `UnifiAuthError` and `LoginFailedException`.
|
|
21
|
+
|
|
22
|
+
class UnifiError(Exception):
|
|
23
|
+
"""Base for all UniFi client errors."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class UnifiAuthError(UnifiError):
|
|
27
|
+
"""Authentication failed (bad credentials, rate limited, locked)."""
|
|
20
28
|
|
|
21
|
-
Attributes:
|
|
22
|
-
http_response_code: The HTTP response code returned by the request.
|
|
23
|
-
curl_getinfo_results: The result of curl_getinfo (or equivalent diagnostics).
|
|
24
|
-
"""
|
|
25
29
|
|
|
26
|
-
|
|
30
|
+
class UnifiTimeoutError(UnifiError):
|
|
31
|
+
"""Connection or request timed out."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class UnifiHTTPError(UnifiError):
|
|
35
|
+
"""HTTP error response (429, 5xx, etc.)."""
|
|
36
|
+
def __init__(self, message='', status_code=None, body=''):
|
|
27
37
|
super().__init__(message)
|
|
38
|
+
self.status_code = status_code
|
|
39
|
+
self.body = body
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class UnifiResponseError(UnifiError):
|
|
43
|
+
"""Controller returned an unparseable or unexpected response."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class UnifiConfigError(UnifiError):
|
|
47
|
+
"""Invalid configuration (bad URL, site name, etc.)."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ── Legacy names (kept for backward compatibility) ────────────────
|
|
51
|
+
#
|
|
52
|
+
# These inherit from the new hierarchy so catching the new names
|
|
53
|
+
# also catches the old ones. Internal library code still raises
|
|
54
|
+
# these; callers can catch either name.
|
|
55
|
+
|
|
56
|
+
class LoginFailedException(UnifiAuthError):
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class LoginRequiredException(UnifiAuthError):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class CurlGeneralErrorException(UnifiHTTPError):
|
|
65
|
+
def __init__(self, message='', http_response_code=None, curl_getinfo_results=None):
|
|
66
|
+
super().__init__(message, status_code=http_response_code, body=curl_getinfo_results or '')
|
|
28
67
|
self._http_response_code = http_response_code
|
|
29
68
|
self._curl_getinfo_results = curl_getinfo_results
|
|
30
69
|
|
|
31
70
|
def get_http_reponse_code(self):
|
|
32
71
|
return self._http_response_code
|
|
33
|
-
|
|
72
|
+
|
|
34
73
|
def get_curl_getinfo_results(self):
|
|
35
74
|
return self._curl_getinfo_results
|
|
36
|
-
class CurlTimeoutException(Exception):
|
|
37
|
-
"""
|
|
38
|
-
Exception raised for cURL timeout errors.
|
|
39
75
|
|
|
40
|
-
Attributes:
|
|
41
|
-
http_response_code: The HTTP response code returned by the request.
|
|
42
|
-
curl_getinfo_results: The result of curl_getinfo (or equivalent diagnostics).
|
|
43
|
-
"""
|
|
44
76
|
|
|
45
|
-
|
|
77
|
+
class CurlTimeoutException(UnifiTimeoutError):
|
|
78
|
+
def __init__(self, message='', http_response_code=None, curl_getinfo_results=None):
|
|
46
79
|
super().__init__(message)
|
|
47
80
|
self._http_response_code = http_response_code
|
|
48
81
|
self._curl_getinfo_results = curl_getinfo_results
|
|
@@ -52,23 +85,42 @@ class CurlTimeoutException(Exception):
|
|
|
52
85
|
|
|
53
86
|
def get_curl_getinfo_results(self):
|
|
54
87
|
return self._curl_getinfo_results
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class JsonDecodeException(UnifiResponseError):
|
|
91
|
+
pass
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class InvalidBaseUrlException(UnifiConfigError):
|
|
59
95
|
def __init__(self, message="The base URL provided is invalid."):
|
|
60
96
|
super().__init__(message)
|
|
61
|
-
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class InvalidSiteNameException(UnifiConfigError):
|
|
100
|
+
def __init__(self):
|
|
101
|
+
super().__init__("Invalid site name provided")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class InvalidCurlMethodException(UnifiConfigError):
|
|
62
105
|
def __init__(self):
|
|
63
106
|
super().__init__("Invalid cURL method provided")
|
|
64
|
-
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class CurlExtensionNotLoadedException(UnifiConfigError):
|
|
65
110
|
def __init__(self):
|
|
66
|
-
super().__init__("
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
class
|
|
70
|
-
|
|
71
|
-
|
|
111
|
+
super().__init__("The Python requests library is not available.")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class EmailInvalidException(UnifiConfigError):
|
|
115
|
+
def __init__(self):
|
|
116
|
+
super().__init__("Invalid email address provided")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class MethodDeprecatedException(UnifiError):
|
|
120
|
+
pass
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class NotAUnifiOsConsoleException(UnifiConfigError):
|
|
72
124
|
def __init__(self):
|
|
73
125
|
super().__init__("This is not a Unifi OS console.")
|
|
74
126
|
|
|
@@ -77,7 +129,7 @@ class Client:
|
|
|
77
129
|
CURL_METHODS_ALLOWED = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']
|
|
78
130
|
DEFAULT_CURL_METHOD = 'GET'
|
|
79
131
|
|
|
80
|
-
def __init__(self, user, password, baseurl='https://
|
|
132
|
+
def __init__(self, user, password, baseurl='https://32.218.193.188', site='default', version='8.0.28', ssl_verify=False, unificookie_name='unificookie', debug=False):
|
|
81
133
|
# Initial setup mirrors PHP constructor
|
|
82
134
|
self._check_curl()
|
|
83
135
|
self._check_base_url(baseurl)
|
|
@@ -109,25 +161,13 @@ class Client:
|
|
|
109
161
|
self._firmware_version = None # None = unknown, 'v1' or 'v2' (auto-detected)
|
|
110
162
|
|
|
111
163
|
self.default_site_stats_attribs = [
|
|
112
|
-
'bytes',
|
|
113
|
-
'
|
|
114
|
-
'wan-rx_bytes',
|
|
115
|
-
'wlan_bytes',
|
|
116
|
-
'num_sta',
|
|
117
|
-
'lan-num_sta',
|
|
118
|
-
'wlan-num_sta',
|
|
119
|
-
'time',
|
|
164
|
+
'bytes', 'wan-tx_bytes', 'wan-rx_bytes', 'wlan_bytes',
|
|
165
|
+
'num_sta', 'lan-num_sta', 'wlan-num_sta', 'time',
|
|
120
166
|
]
|
|
121
167
|
|
|
122
168
|
self.default_ap_stats_attribs = [
|
|
123
|
-
'bytes',
|
|
124
|
-
'
|
|
125
|
-
'wan-rx_bytes',
|
|
126
|
-
'wlan_bytes',
|
|
127
|
-
'num_sta',
|
|
128
|
-
'lan-num_sta',
|
|
129
|
-
'wlan-num_sta',
|
|
130
|
-
'time',
|
|
169
|
+
'bytes', 'wan-tx_bytes', 'wan-rx_bytes', 'wlan_bytes',
|
|
170
|
+
'num_sta', 'lan-num_sta', 'wlan-num_sta', 'time',
|
|
131
171
|
]
|
|
132
172
|
|
|
133
173
|
if self.debug:
|
|
@@ -167,7 +207,7 @@ class Client:
|
|
|
167
207
|
return True
|
|
168
208
|
return False
|
|
169
209
|
|
|
170
|
-
def login(self, return_token:bool=False) -> bool:
|
|
210
|
+
def login(self, return_token: bool = False) -> bool:
|
|
171
211
|
# Skip if already logged in via valid cookie
|
|
172
212
|
self._verify_ssl_cert = False
|
|
173
213
|
|
|
@@ -279,6 +319,11 @@ class Client:
|
|
|
279
319
|
|
|
280
320
|
return True
|
|
281
321
|
|
|
322
|
+
def _request(self, path: str, method: str = 'GET', payload=None):
|
|
323
|
+
"""Simple HTTP request wrapper. Sets method, calls fetch_results with network proxy."""
|
|
324
|
+
self._curl_method = method
|
|
325
|
+
return self.fetch_results(path, payload, proxy_type='network')
|
|
326
|
+
|
|
282
327
|
# === API Endpoint Methods ===
|
|
283
328
|
# The following methods are directly converted from the PHP class to Python, preserving functionality and parameters.
|
|
284
329
|
|
|
@@ -286,16 +331,16 @@ class Client:
|
|
|
286
331
|
return self.fetch_results(f"/api/s/{self._site}/stat/sysinfo", proxy_type='network')
|
|
287
332
|
|
|
288
333
|
def get_clients(self):
|
|
289
|
-
return self.
|
|
334
|
+
return self._request(f"/api/s/{self._site}/stat/sta")
|
|
290
335
|
|
|
291
336
|
def block_client(self, mac):
|
|
292
|
-
return self.
|
|
337
|
+
return self._request(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload={'cmd': 'block-sta', 'mac': mac})
|
|
293
338
|
|
|
294
339
|
def unblock_client(self, mac):
|
|
295
|
-
return self.
|
|
340
|
+
return self._request(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload={'cmd': 'unblock-sta', 'mac': mac})
|
|
296
341
|
|
|
297
342
|
def reconnect_client(self, mac):
|
|
298
|
-
return self.
|
|
343
|
+
return self._request(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload={'cmd': 'kick-sta', 'mac': mac})
|
|
299
344
|
|
|
300
345
|
def authorize_guest(self, mac, minutes, up=None, down=None, megabytes=None, ap_mac=None):
|
|
301
346
|
payload = {
|
|
@@ -307,7 +352,7 @@ class Client:
|
|
|
307
352
|
if down is not None: payload['down'] = down
|
|
308
353
|
if megabytes is not None: payload['bytes'] = megabytes
|
|
309
354
|
if ap_mac is not None: payload['ap_mac'] = ap_mac.lower()
|
|
310
|
-
return self.
|
|
355
|
+
return self._request(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload=payload)
|
|
311
356
|
|
|
312
357
|
"""
|
|
313
358
|
Unauthorize a client device.
|
|
@@ -317,32 +362,37 @@ class Client:
|
|
|
317
362
|
throws Exception
|
|
318
363
|
"""
|
|
319
364
|
def unauthorize_guest(self, mac):
|
|
320
|
-
return self.
|
|
365
|
+
return self._request(
|
|
321
366
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
367
|
+
method='POST',
|
|
322
368
|
payload={'cmd': 'unauthorize-guest', 'mac': mac}
|
|
323
369
|
)
|
|
324
370
|
|
|
325
371
|
def reconnect_sta(self, mac):
|
|
326
|
-
return self.
|
|
372
|
+
return self._request(
|
|
327
373
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
374
|
+
method='POST',
|
|
328
375
|
payload={'cmd': 'kick-sta', 'mac': mac.lower()}
|
|
329
376
|
)
|
|
330
377
|
|
|
331
378
|
def block_sta(self, mac):
|
|
332
|
-
return self.
|
|
379
|
+
return self._request(
|
|
333
380
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
381
|
+
method='POST',
|
|
334
382
|
payload={'cmd': 'block-sta', 'mac': mac.lower()}
|
|
335
383
|
)
|
|
336
384
|
|
|
337
385
|
def unblock_sta(self, mac):
|
|
338
|
-
return self.
|
|
386
|
+
return self._request(
|
|
339
387
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
388
|
+
method='POST',
|
|
340
389
|
payload={'cmd': 'unblock-sta', 'mac': mac.lower()}
|
|
341
390
|
)
|
|
342
391
|
|
|
343
392
|
def forget_sta(self, mac):
|
|
344
|
-
return self.
|
|
393
|
+
return self._request(
|
|
345
394
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
395
|
+
method='POST',
|
|
346
396
|
payload={'cmd': 'forget-sta', 'mac': mac}
|
|
347
397
|
)
|
|
348
398
|
|
|
@@ -386,15 +436,14 @@ class Client:
|
|
|
386
436
|
|
|
387
437
|
return self.fetch_results(
|
|
388
438
|
f"/api/s/{self._site}/rest/user",
|
|
389
|
-
payload=payload
|
|
390
|
-
proxy_type='network'
|
|
439
|
+
payload=payload
|
|
391
440
|
)
|
|
392
441
|
|
|
393
442
|
def delete_user(self, user_id: str):
|
|
394
443
|
"""
|
|
395
444
|
Remove a user by ID
|
|
396
445
|
"""
|
|
397
|
-
return self.
|
|
446
|
+
return self._request(f"/api/s/{self._site}/rest/user/{user_id}", method='DELETE')
|
|
398
447
|
|
|
399
448
|
def get_user(self, user_id: str):
|
|
400
449
|
"""
|
|
@@ -403,7 +452,7 @@ class Client:
|
|
|
403
452
|
return self.fetch_results(f"/api/s/{self._site}/rest/user/{user_id}")
|
|
404
453
|
|
|
405
454
|
def get_client_by_mac(self, mac: str):
|
|
406
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/user/{mac}"
|
|
455
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/user/{mac}")
|
|
407
456
|
|
|
408
457
|
def update_user(self, user_id: str, name: str = None, note: str = None, is_guest: bool = None, is_wired: bool = None):
|
|
409
458
|
"""
|
|
@@ -422,16 +471,16 @@ class Client:
|
|
|
422
471
|
|
|
423
472
|
return self.fetch_results(
|
|
424
473
|
f"/api/s/{self._site}/rest/user/{user_id}",
|
|
425
|
-
payload=payload
|
|
426
|
-
proxy_type='network'
|
|
474
|
+
payload=payload
|
|
427
475
|
)
|
|
428
476
|
|
|
429
477
|
def forget_user(self, mac: str):
|
|
430
478
|
"""
|
|
431
479
|
Forget (remove) any record of a client's MAC from the site.
|
|
432
480
|
"""
|
|
433
|
-
return self.
|
|
481
|
+
return self._request(
|
|
434
482
|
f"/api/s/{self._site}/cmd/sitemgr",
|
|
483
|
+
method='POST',
|
|
435
484
|
payload={'cmd': 'forget-sta', 'mac': mac}
|
|
436
485
|
)
|
|
437
486
|
|
|
@@ -439,13 +488,13 @@ class Client:
|
|
|
439
488
|
|
|
440
489
|
## ------------- Make sure these are included in the PHP files ------
|
|
441
490
|
def get_clients_summary(self):
|
|
442
|
-
return self.
|
|
491
|
+
return self._request(f"/api/s/{self._site}/stat/summary/client")
|
|
443
492
|
|
|
444
493
|
def get_user_groups(self):
|
|
445
|
-
return self.
|
|
494
|
+
return self._request(f"/api/s/{self._site}/list/usergroup")
|
|
446
495
|
|
|
447
496
|
def get_user_group(self, group_id):
|
|
448
|
-
return self.
|
|
497
|
+
return self._request(f"/api/s/{self._site}/list/usergroup/{group_id}")
|
|
449
498
|
|
|
450
499
|
def create_user_group(self, group_name: str, group_dn: int = -1, group_up: int = -1):
|
|
451
500
|
"""
|
|
@@ -476,25 +525,27 @@ class Client:
|
|
|
476
525
|
'qos_rate_max_up': group_up,
|
|
477
526
|
'site_id': site_id,
|
|
478
527
|
}
|
|
479
|
-
return self.
|
|
528
|
+
return self._request(
|
|
480
529
|
f"/api/s/{self._site}/rest/usergroup",
|
|
530
|
+
method='PUT',
|
|
481
531
|
payload=payload
|
|
482
532
|
)
|
|
483
533
|
|
|
484
534
|
def delete_user_group(self, group_id):
|
|
485
|
-
return self.
|
|
535
|
+
return self._request(
|
|
486
536
|
f"/api/s/{self._site}/cmd/usergroup/{group_id}",
|
|
537
|
+
method='DELETE'
|
|
487
538
|
)
|
|
488
539
|
|
|
489
540
|
|
|
490
541
|
def list_sites(self):
|
|
491
|
-
return self.fetch_results("/api/self/sites"
|
|
542
|
+
return self.fetch_results("/api/self/sites")
|
|
492
543
|
|
|
493
544
|
def list_apgroups(self):
|
|
494
545
|
"""
|
|
495
546
|
Fetch AP groups for the current site.
|
|
496
547
|
"""
|
|
497
|
-
return self.
|
|
548
|
+
return self._request(f"/v2/api/site/{self._site}/apgroups")
|
|
498
549
|
|
|
499
550
|
def create_apgroup(self, name: str, description: str = None) -> dict:
|
|
500
551
|
"""Create a new AP group with optional description."""
|
|
@@ -525,7 +576,7 @@ class Client:
|
|
|
525
576
|
def list_dashboard(self, five_minutes: bool = False):
|
|
526
577
|
"""Fetch dashboard metrics, 5-minute scale if requested."""
|
|
527
578
|
suffix = '?scale=5minutes' if five_minutes else ''
|
|
528
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/dashboard{suffix}"
|
|
579
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/dashboard{suffix}")
|
|
529
580
|
|
|
530
581
|
def list_users(self):
|
|
531
582
|
"""Fetch known client devices."""
|
|
@@ -559,7 +610,7 @@ class Client:
|
|
|
559
610
|
return self.fetch_results(f"/api/s/{self._site}/rest/rogueknown")
|
|
560
611
|
|
|
561
612
|
def get_site(self, site_id) -> str:
|
|
562
|
-
return self.
|
|
613
|
+
return self._request(f"/api/s/{site_id}/self")
|
|
563
614
|
|
|
564
615
|
def create_site(self, description: str):
|
|
565
616
|
"""
|
|
@@ -588,8 +639,9 @@ class Client:
|
|
|
588
639
|
self._curl_method = "GET"
|
|
589
640
|
|
|
590
641
|
def delete_site(self, site_id):
|
|
591
|
-
return self.
|
|
642
|
+
return self._request(
|
|
592
643
|
f"/api/s/{site_id}",
|
|
644
|
+
method='DELETE',
|
|
593
645
|
payload={'site': site_id, 'cmd': 'delete-site'}
|
|
594
646
|
)
|
|
595
647
|
|
|
@@ -658,7 +710,7 @@ class Client:
|
|
|
658
710
|
def list_all_admins(self):
|
|
659
711
|
"""Fetch all administrators"""
|
|
660
712
|
payload = {'cmd': 'get-all-admins'}
|
|
661
|
-
return self.fetch_results(f"/api/s/{self._site}/cmd/sitemgr", payload=payload
|
|
713
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
662
714
|
|
|
663
715
|
def invite_admin(self, name: str, email: str, enable_sso: bool = True, readonly: bool = False,
|
|
664
716
|
device_adopt: bool = False, device_restart: bool = False) -> bool:
|
|
@@ -678,7 +730,7 @@ class Client:
|
|
|
678
730
|
payload['permissions'].append('API_DEVICE_ADOPT')
|
|
679
731
|
if device_restart:
|
|
680
732
|
payload['permissions'].append('API_DEVICE_RESTART')
|
|
681
|
-
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload
|
|
733
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
682
734
|
|
|
683
735
|
def assign_existing_admin(self, admin_id: str, readonly: bool = False,
|
|
684
736
|
device_adopt: bool = False, device_restart: bool = False) -> bool:
|
|
@@ -710,12 +762,12 @@ class Client:
|
|
|
710
762
|
def revoke_admin(self, admin_id: str) -> bool:
|
|
711
763
|
"""Revoke an admin's access to this site"""
|
|
712
764
|
payload = {'cmd': 'revoke-admin', 'admin': admin_id.strip()}
|
|
713
|
-
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload
|
|
765
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
714
766
|
|
|
715
767
|
def delete_admin(self, admin_id: str) -> bool:
|
|
716
768
|
"""Delete an admin user"""
|
|
717
769
|
payload = {'cmd': 'delete-admin', 'admin': admin_id.strip()}
|
|
718
|
-
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload
|
|
770
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
719
771
|
|
|
720
772
|
def list_wlan_groups(self):
|
|
721
773
|
"""Fetch WLAN groups"""
|
|
@@ -730,8 +782,7 @@ class Client:
|
|
|
730
782
|
return self.fetch_results_boolean(
|
|
731
783
|
'/status',
|
|
732
784
|
payload=None,
|
|
733
|
-
login_required=self._unifi_os
|
|
734
|
-
proxy_type='network'
|
|
785
|
+
login_required=self._unifi_os
|
|
735
786
|
)
|
|
736
787
|
|
|
737
788
|
def stat_full_status(self):
|
|
@@ -740,8 +791,7 @@ class Client:
|
|
|
740
791
|
self.fetch_results_boolean(
|
|
741
792
|
'/status',
|
|
742
793
|
payload=None,
|
|
743
|
-
login_required=self._unifi_os
|
|
744
|
-
proxy_type='network'
|
|
794
|
+
login_required=self._unifi_os
|
|
745
795
|
)
|
|
746
796
|
# Decode and return the last raw JSON results
|
|
747
797
|
raw = self.get_last_results_raw(return_json=False)
|
|
@@ -773,230 +823,19 @@ class Client:
|
|
|
773
823
|
return self.fetch_results(f"/api/s/{self._site}/stat/device", login_required=True, proxy_type='network')
|
|
774
824
|
|
|
775
825
|
def get_device(self, device_id):
|
|
776
|
-
return self.
|
|
777
|
-
|
|
778
|
-
# === Health & Status Methods ===
|
|
779
|
-
|
|
780
|
-
def list_health(self):
|
|
781
|
-
"""Get site health status including WAN, LAN, WLAN subsystems.
|
|
782
|
-
|
|
783
|
-
Returns:
|
|
784
|
-
list: Health data for each subsystem with status and details
|
|
785
|
-
"""
|
|
786
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/health", proxy_type='network')
|
|
826
|
+
return self._request(f"/api/s/{self._site}/stat/device/{device_id}")
|
|
787
827
|
|
|
788
|
-
def get_device_history(self, mac: str, is_client:bool, limit: int = 50):
|
|
789
|
-
"""Fetch device activity/event history from system logs.
|
|
790
|
-
|
|
791
|
-
Args:
|
|
792
|
-
mac: Device MAC address
|
|
793
|
-
is_client: Determines the scope, 'CLIENTS or DEVICE'
|
|
794
|
-
limit: Maximum number of entries to return
|
|
795
|
-
|
|
796
|
-
Returns:
|
|
797
|
-
list: Activity log entries for the device
|
|
798
|
-
"""
|
|
799
|
-
scope = 'CLIENTS' if is_client else 'DEVICE'
|
|
800
|
-
|
|
801
|
-
self._curl_method = 'GET'
|
|
802
|
-
return self.fetch_results(
|
|
803
|
-
f"/v2/api/site/default/system-log/device/{mac}?mac={mac}&scope={scope}&limit={limit}",
|
|
804
|
-
proxy_type='network'
|
|
805
|
-
)
|
|
806
|
-
|
|
807
|
-
# === Firewall Methods ===
|
|
808
|
-
|
|
809
|
-
def list_firewall_rules(self):
|
|
810
|
-
"""List all firewall rules for the site.
|
|
811
|
-
|
|
812
|
-
Returns:
|
|
813
|
-
list: Firewall rule configurations
|
|
814
|
-
"""
|
|
815
|
-
return self.fetch_results(f"/api/s/{self._site}/rest/firewallrule", proxy_type='network')
|
|
816
|
-
|
|
817
|
-
def create_firewall_rule(self, payload: dict):
|
|
818
|
-
"""Create a new firewall rule.
|
|
819
|
-
|
|
820
|
-
Args:
|
|
821
|
-
payload: Firewall rule configuration dict
|
|
822
|
-
|
|
823
|
-
Returns:
|
|
824
|
-
list: Created firewall rule data
|
|
825
|
-
"""
|
|
826
|
-
self._curl_method = 'POST'
|
|
827
|
-
return self.fetch_results(f"/api/s/{self._site}/rest/firewallrule", payload=payload, proxy_type='network')
|
|
828
|
-
|
|
829
|
-
def delete_firewall_rule(self, rule_id: str):
|
|
830
|
-
"""Delete a firewall rule by ID.
|
|
831
|
-
|
|
832
|
-
Args:
|
|
833
|
-
rule_id: The _id of the firewall rule to delete
|
|
834
|
-
|
|
835
|
-
Returns:
|
|
836
|
-
bool: True if successful
|
|
837
|
-
"""
|
|
838
|
-
self._curl_method = 'DELETE'
|
|
839
|
-
return self.fetch_results_boolean(f"/api/s/{self._site}/rest/firewallrule/{rule_id}", proxy_type='network')
|
|
840
|
-
|
|
841
|
-
# === UniFi OS System Methods (no prefix_path - direct /api/ endpoints) ===
|
|
842
|
-
|
|
843
|
-
def get_system_config(self):
|
|
844
|
-
"""Get UniFi OS system configuration.
|
|
845
|
-
|
|
846
|
-
Returns:
|
|
847
|
-
list: System configuration including SSH, update settings
|
|
848
|
-
"""
|
|
849
|
-
return self.fetch_results("/api/system", proxy_type=None)
|
|
850
|
-
|
|
851
|
-
def set_system_config(self, payload: dict):
|
|
852
|
-
"""Update UniFi OS system configuration.
|
|
853
|
-
|
|
854
|
-
Args:
|
|
855
|
-
payload: System config updates (e.g., {'ssh': {'enabled': True}})
|
|
856
|
-
|
|
857
|
-
Returns:
|
|
858
|
-
list: Updated system configuration
|
|
859
|
-
"""
|
|
860
|
-
self._curl_method = 'PATCH'
|
|
861
|
-
return self.fetch_results("/api/system", payload=payload, proxy_type=None)
|
|
862
|
-
|
|
863
|
-
def set_ssh_password(self, password: str):
|
|
864
|
-
"""Set the SSH password for UniFi OS.
|
|
865
|
-
|
|
866
|
-
Args:
|
|
867
|
-
password: New SSH password
|
|
868
|
-
|
|
869
|
-
Returns:
|
|
870
|
-
list: Response from password set operation
|
|
871
|
-
"""
|
|
872
|
-
self._curl_method = 'POST'
|
|
873
|
-
return self.fetch_results("/api/system/ssh/setpassword", payload={'password': password}, proxy_type=None)
|
|
874
|
-
|
|
875
|
-
def get_notification_settings(self):
|
|
876
|
-
"""Get UniFi OS notification settings.
|
|
877
|
-
|
|
878
|
-
Returns:
|
|
879
|
-
list: Notification configuration
|
|
880
|
-
"""
|
|
881
|
-
return self.fetch_results("/api/notifications/settings", proxy_type=None)
|
|
882
|
-
|
|
883
|
-
def set_notification_settings(self, payload: dict):
|
|
884
|
-
"""Update UniFi OS notification settings.
|
|
885
|
-
|
|
886
|
-
Args:
|
|
887
|
-
payload: Notification settings to update
|
|
888
|
-
|
|
889
|
-
Returns:
|
|
890
|
-
list: Updated notification settings
|
|
891
|
-
"""
|
|
892
|
-
self._curl_method = 'PUT'
|
|
893
|
-
return self.fetch_results("/api/notifications/settings", payload=payload, proxy_type=None)
|
|
894
|
-
|
|
895
|
-
def download_backup(self, filename: str = None):
|
|
896
|
-
"""Download UniFi OS system backup.
|
|
897
|
-
|
|
898
|
-
Args:
|
|
899
|
-
filename: Optional filename filter
|
|
900
|
-
|
|
901
|
-
Returns:
|
|
902
|
-
bytes: Backup file content (requires special handling for binary data)
|
|
903
|
-
"""
|
|
904
|
-
params = {}
|
|
905
|
-
if filename:
|
|
906
|
-
params['filename'] = filename
|
|
907
|
-
self._curl_method = 'GET'
|
|
908
|
-
# Note: This returns raw bytes, not JSON - may need special handling
|
|
909
|
-
return self.exec_curl("/api/backup/download", payload=params if params else None, proxy_type=None)
|
|
910
|
-
|
|
911
|
-
# === User Management Methods (always /proxy/users/ - no v1/v2 distinction) ===
|
|
912
|
-
|
|
913
|
-
def list_site_users(self):
|
|
914
|
-
"""Get all users/admins for the site.
|
|
915
|
-
|
|
916
|
-
Returns:
|
|
917
|
-
list: User accounts with roles and permissions
|
|
918
|
-
"""
|
|
919
|
-
return self.fetch_results("/api/v2/users", proxy_type='users')
|
|
920
|
-
|
|
921
|
-
def invite_user(self, email: str, role: str = 'admin', permissions: dict = None):
|
|
922
|
-
"""Invite a user to the UniFi site.
|
|
923
|
-
|
|
924
|
-
Args:
|
|
925
|
-
email: User's email address
|
|
926
|
-
role: User role (e.g., 'admin', 'viewer')
|
|
927
|
-
permissions: Optional permission overrides
|
|
928
|
-
|
|
929
|
-
Returns:
|
|
930
|
-
list: Invitation result
|
|
931
|
-
"""
|
|
932
|
-
payload = {
|
|
933
|
-
'email': email,
|
|
934
|
-
'role': role
|
|
935
|
-
}
|
|
936
|
-
if permissions:
|
|
937
|
-
payload['permissions'] = permissions
|
|
938
|
-
self._curl_method = 'POST'
|
|
939
|
-
return self.fetch_results("/api/v2/users/invite_add", payload=payload, proxy_type='users')
|
|
940
|
-
|
|
941
|
-
def deactivate_user(self, user_id: str):
|
|
942
|
-
"""Deactivate a user account.
|
|
943
|
-
|
|
944
|
-
Args:
|
|
945
|
-
user_id: User's unique identifier
|
|
946
|
-
|
|
947
|
-
Returns:
|
|
948
|
-
list: Deactivation result
|
|
949
|
-
"""
|
|
950
|
-
self._curl_method = 'PUT'
|
|
951
|
-
return self.fetch_results(f"/api/v2/user/{user_id}/deactivate?isULP=1", proxy_type='users')
|
|
952
|
-
|
|
953
|
-
def activate_user(self, user_id: str):
|
|
954
|
-
"""Activate a deactivated user account.
|
|
955
|
-
|
|
956
|
-
Args:
|
|
957
|
-
user_id: User's unique identifier
|
|
958
|
-
|
|
959
|
-
Returns:
|
|
960
|
-
list: Activation result
|
|
961
|
-
"""
|
|
962
|
-
self._curl_method = 'PUT'
|
|
963
|
-
return self.fetch_results(f"/api/v2/user/{user_id}/active?isULP=1", proxy_type='users')
|
|
964
|
-
|
|
965
|
-
def remove_user(self, user_id: str):
|
|
966
|
-
"""Permanently remove a user account.
|
|
967
|
-
|
|
968
|
-
Args:
|
|
969
|
-
user_id: User's unique identifier
|
|
970
|
-
|
|
971
|
-
Returns:
|
|
972
|
-
list: Removal result
|
|
973
|
-
"""
|
|
974
|
-
self._curl_method = 'DELETE'
|
|
975
|
-
return self.fetch_results(f"/api/v2/user/{user_id}", proxy_type='users')
|
|
976
|
-
|
|
977
|
-
def create_custom_role(self, payload: dict):
|
|
978
|
-
"""Create a custom permission role.
|
|
979
|
-
|
|
980
|
-
Args:
|
|
981
|
-
payload: Role configuration with permissions
|
|
982
|
-
|
|
983
|
-
Returns:
|
|
984
|
-
list: Created role data
|
|
985
|
-
"""
|
|
986
|
-
self._curl_method = 'POST'
|
|
987
|
-
return self.fetch_results("/api/v2/custom_role", payload=payload, proxy_type='users')
|
|
988
|
-
|
|
989
828
|
def get_wlan(self, wlan_id: str):
|
|
990
829
|
"""
|
|
991
830
|
Retrieve WLAN configuration by ID
|
|
992
831
|
"""
|
|
993
|
-
return self.
|
|
832
|
+
return self._request(f"/api/s/{self._site}/rest/wlanconf/{wlan_id}")
|
|
994
833
|
|
|
995
834
|
def list_wlanconf(self):
|
|
996
835
|
"""
|
|
997
836
|
List all WLAN configurations on the site.
|
|
998
837
|
"""
|
|
999
|
-
return self.
|
|
838
|
+
return self._request(f"/api/s/{self._site}/rest/wlanconf")
|
|
1000
839
|
|
|
1001
840
|
def create_wlan(
|
|
1002
841
|
self,
|
|
@@ -1045,8 +884,9 @@ class Client:
|
|
|
1045
884
|
data['ap_group_ids'] = ap_group_ids
|
|
1046
885
|
|
|
1047
886
|
# Perform the request and return True on HTTP 200
|
|
1048
|
-
self.
|
|
887
|
+
self._request(
|
|
1049
888
|
f"/api/s/{self._site}/add/wlanconf",
|
|
889
|
+
method='POST',
|
|
1050
890
|
payload=data
|
|
1051
891
|
)
|
|
1052
892
|
return self._last_response_code == 200
|
|
@@ -1089,8 +929,9 @@ class Client:
|
|
|
1089
929
|
data['x_passphrase'] = x_passphrase.strip()
|
|
1090
930
|
if name is not None:
|
|
1091
931
|
data['name'] = name.strip()
|
|
1092
|
-
return self.
|
|
932
|
+
return self._request(
|
|
1093
933
|
f"/api/s/{self._site}/rest/wlanconf/{wlan_id}",
|
|
934
|
+
method='PUT',
|
|
1094
935
|
payload=data
|
|
1095
936
|
)
|
|
1096
937
|
|
|
@@ -1098,7 +939,7 @@ class Client:
|
|
|
1098
939
|
"""
|
|
1099
940
|
Delete a WLAN configuration by ID
|
|
1100
941
|
"""
|
|
1101
|
-
return self.
|
|
942
|
+
return self._request(
|
|
1102
943
|
f"/api/s/{self._site}/rest/wlanconf/{wlan_id.strip()}"
|
|
1103
944
|
)
|
|
1104
945
|
|
|
@@ -1151,7 +992,7 @@ class Client:
|
|
|
1151
992
|
def list_clients(self, mac: str = None):
|
|
1152
993
|
"""Fetch online client devices, or single device if MAC provided."""
|
|
1153
994
|
path_mac = mac.lower().strip() if isinstance(mac, str) else ''
|
|
1154
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/sta/{path_mac}"
|
|
995
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/sta/{path_mac}")
|
|
1155
996
|
|
|
1156
997
|
def list_active_clients(self, include_traffic_usage: bool = True, include_unifi_devices: bool = True):
|
|
1157
998
|
"""Fetch active client devices, with optional traffic and UniFi device inclusion."""
|
|
@@ -1159,7 +1000,7 @@ class Client:
|
|
|
1159
1000
|
'include_traffic_usage': include_traffic_usage,
|
|
1160
1001
|
'include_unifi_devices': include_unifi_devices,
|
|
1161
1002
|
})
|
|
1162
|
-
return self.fetch_results(f"/v2/api/site/{self._site}/clients/active?{query}"
|
|
1003
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/clients/active?{query}")
|
|
1163
1004
|
|
|
1164
1005
|
def list_clients_history(self, only_non_blocked: bool = True, include_unifi_devices: bool = True, within_hours: int = 0):
|
|
1165
1006
|
"""Fetch offline client device history."""
|
|
@@ -1174,8 +1015,9 @@ class Client:
|
|
|
1174
1015
|
"""
|
|
1175
1016
|
Expire (unauthorize) a guest session immedietely
|
|
1176
1017
|
"""
|
|
1177
|
-
return self.
|
|
1018
|
+
return self._request(
|
|
1178
1019
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
1020
|
+
method='POST',
|
|
1179
1021
|
payload={'cmd': 'unauthorize-guest', 'mac': mac}
|
|
1180
1022
|
)
|
|
1181
1023
|
|
|
@@ -1183,7 +1025,7 @@ class Client:
|
|
|
1183
1025
|
"""
|
|
1184
1026
|
List all hotspot vouchers on the site.
|
|
1185
1027
|
"""
|
|
1186
|
-
return self.
|
|
1028
|
+
return self._request(f"/api/s/{self._site}/stat/voucher")
|
|
1187
1029
|
|
|
1188
1030
|
def create_voucher(
|
|
1189
1031
|
self,
|
|
@@ -1221,8 +1063,9 @@ class Client:
|
|
|
1221
1063
|
if megabytes is not None:
|
|
1222
1064
|
payload['bytes'] = megabytes
|
|
1223
1065
|
|
|
1224
|
-
return self.
|
|
1066
|
+
return self._request(
|
|
1225
1067
|
f"/api/s/{self._site}/cmd/hotspot",
|
|
1068
|
+
method='POST',
|
|
1226
1069
|
payload=payload
|
|
1227
1070
|
)
|
|
1228
1071
|
|
|
@@ -1234,8 +1077,9 @@ class Client:
|
|
|
1234
1077
|
"""
|
|
1235
1078
|
payload = {'_id': voucher_id, 'cmd': 'delete-voucher'}
|
|
1236
1079
|
|
|
1237
|
-
return self.
|
|
1080
|
+
return self._request(
|
|
1238
1081
|
f"/api/s/{self._site}/cmd/hotspot",
|
|
1082
|
+
method='POST',
|
|
1239
1083
|
payload=payload
|
|
1240
1084
|
)
|
|
1241
1085
|
|
|
@@ -1243,7 +1087,7 @@ class Client:
|
|
|
1243
1087
|
"""
|
|
1244
1088
|
List all client sessions (stat/session) for the site
|
|
1245
1089
|
"""
|
|
1246
|
-
return self.
|
|
1090
|
+
return self._request(f"/api/s/{self._site}/stat/session")
|
|
1247
1091
|
|
|
1248
1092
|
def stat_hourly_site(self, start: int = None, end: int = None, attribs: list = None):
|
|
1249
1093
|
"""
|
|
@@ -1264,8 +1108,9 @@ class Client:
|
|
|
1264
1108
|
'end': end
|
|
1265
1109
|
}
|
|
1266
1110
|
|
|
1267
|
-
return self.
|
|
1111
|
+
return self._request(
|
|
1268
1112
|
f"/api/s/{self._site}/stat/report/hourly.site",
|
|
1113
|
+
method='GET',
|
|
1269
1114
|
payload=payload
|
|
1270
1115
|
)
|
|
1271
1116
|
|
|
@@ -1275,7 +1120,7 @@ class Client:
|
|
|
1275
1120
|
start = start or end - 12 * 3600 * 1000
|
|
1276
1121
|
attrs = attribs or self.default_site_stats_attribs
|
|
1277
1122
|
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1278
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.site", payload=payload
|
|
1123
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.site", payload=payload)
|
|
1279
1124
|
|
|
1280
1125
|
def stat_5minutes_aps(self, start: int = None, end: int = None, mac: str = None, attribs: list = None):
|
|
1281
1126
|
"""Fetch 5-minute AP stats (defaults to past 12 hours)."""
|
|
@@ -1285,7 +1130,7 @@ class Client:
|
|
|
1285
1130
|
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1286
1131
|
if mac:
|
|
1287
1132
|
payload['mac'] = mac.lower()
|
|
1288
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.ap", payload=payload
|
|
1133
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.ap", payload=payload)
|
|
1289
1134
|
|
|
1290
1135
|
def stat_hourly_aps(self, start: int = None, end: int = None, mac: str = None, attribs: list = None):
|
|
1291
1136
|
"""Fetch hourly AP stats (defaults to past 7 days)."""
|
|
@@ -1366,7 +1211,7 @@ class Client:
|
|
|
1366
1211
|
start = start or end - 12 * 3600 * 1000
|
|
1367
1212
|
attrs = attribs or ['time', 'mem', 'cpu', 'loadavg_5']
|
|
1368
1213
|
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1369
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.gw", payload=payload
|
|
1214
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.gw", payload=payload)
|
|
1370
1215
|
|
|
1371
1216
|
def stat_hourly_gateway(self, start: int = None, end: int = None, attribs: list = None):
|
|
1372
1217
|
"""Fetch hourly gateway stats (defaults to past 7 days)."""
|
|
@@ -1395,10 +1240,10 @@ class Client:
|
|
|
1395
1240
|
return self.fetch_results(f"/api/s/{self._site}/stat/report/monthly.gw", payload=payload)
|
|
1396
1241
|
|
|
1397
1242
|
def list_network(self, network_id: str = ''):
|
|
1398
|
-
return self.
|
|
1243
|
+
return self._request(f"/api/s/{self._site}/rest/networkconf{network_id.strip()}")
|
|
1399
1244
|
|
|
1400
1245
|
def list_networkconf(self, network_id: str = ''):
|
|
1401
|
-
return self.
|
|
1246
|
+
return self._request(f"/api/s/{self._site}/rest/networkconf{network_id.strip()}")
|
|
1402
1247
|
|
|
1403
1248
|
def list_backups(self):
|
|
1404
1249
|
payload = {'cmd': 'list-backups'}
|
|
@@ -1409,14 +1254,15 @@ class Client:
|
|
|
1409
1254
|
"""
|
|
1410
1255
|
Get a specific network configuration by ID
|
|
1411
1256
|
"""
|
|
1412
|
-
return self.
|
|
1257
|
+
return self._request(f"/api/s/{self._site}/rest/networkconf/{network_id}")
|
|
1413
1258
|
|
|
1414
1259
|
def create_network(self, payload: dict):
|
|
1415
1260
|
"""
|
|
1416
1261
|
Create a new network configuration
|
|
1417
1262
|
"""
|
|
1418
|
-
return self.
|
|
1263
|
+
return self._request(
|
|
1419
1264
|
f"/api/s/{self._site}/rest/networkconf",
|
|
1265
|
+
method='POST',
|
|
1420
1266
|
payload=payload
|
|
1421
1267
|
)
|
|
1422
1268
|
|
|
@@ -1424,8 +1270,9 @@ class Client:
|
|
|
1424
1270
|
"""
|
|
1425
1271
|
Update an existing network configuration
|
|
1426
1272
|
"""
|
|
1427
|
-
return self.
|
|
1273
|
+
return self._request(
|
|
1428
1274
|
f"/api/s/{self._site}/rest/networkconf/{network_id}",
|
|
1275
|
+
method='PUT',
|
|
1429
1276
|
payload=update_fields
|
|
1430
1277
|
)
|
|
1431
1278
|
|
|
@@ -1433,28 +1280,30 @@ class Client:
|
|
|
1433
1280
|
"""
|
|
1434
1281
|
Delete a network configuration by ID
|
|
1435
1282
|
"""
|
|
1436
|
-
return self.
|
|
1283
|
+
return self._request(
|
|
1437
1284
|
f"/api/s/{self._site}/rest/networkconf{network_id.strip()}",
|
|
1285
|
+
method='DELETE'
|
|
1438
1286
|
)
|
|
1439
1287
|
|
|
1440
1288
|
def list_portconf(self):
|
|
1441
1289
|
"""
|
|
1442
1290
|
List all port configurations on the site.
|
|
1443
1291
|
"""
|
|
1444
|
-
return self.
|
|
1292
|
+
return self._request(f"/api/s/{self._site}/list/portconf")
|
|
1445
1293
|
|
|
1446
1294
|
def get_portconf(self, portconf_id: str):
|
|
1447
1295
|
"""
|
|
1448
1296
|
Retrieve port configuration by ID
|
|
1449
1297
|
"""
|
|
1450
|
-
return self.
|
|
1298
|
+
return self._request(f"/api/s/{self._site}/rest/portconf/{portconf_id}")
|
|
1451
1299
|
|
|
1452
1300
|
def create_portconf(self, config: dict):
|
|
1453
1301
|
"""
|
|
1454
1302
|
Create a new port configuration.
|
|
1455
1303
|
"""
|
|
1456
|
-
return self.
|
|
1304
|
+
return self._request(
|
|
1457
1305
|
f"/api/s/{self._site}/rest/portconf",
|
|
1306
|
+
method='POST',
|
|
1458
1307
|
payload=config
|
|
1459
1308
|
)
|
|
1460
1309
|
|
|
@@ -1462,8 +1311,9 @@ class Client:
|
|
|
1462
1311
|
"""
|
|
1463
1312
|
Update an existing port configuration.
|
|
1464
1313
|
"""
|
|
1465
|
-
return self.
|
|
1314
|
+
return self._request(
|
|
1466
1315
|
f"/api/s/{self._site}/rest/portconf/{portconf_id}",
|
|
1316
|
+
method='PUT',
|
|
1467
1317
|
payload=config
|
|
1468
1318
|
)
|
|
1469
1319
|
|
|
@@ -1471,8 +1321,9 @@ class Client:
|
|
|
1471
1321
|
"""
|
|
1472
1322
|
Delete a port configuration by ID.
|
|
1473
1323
|
"""
|
|
1474
|
-
return self.
|
|
1324
|
+
return self._request(
|
|
1475
1325
|
f"/api/s/{self._site}/rest/portconf/{portconf_id}",
|
|
1326
|
+
method='DELETE'
|
|
1476
1327
|
)
|
|
1477
1328
|
|
|
1478
1329
|
def stat_ips_events(self, start: int = None, end: int = None, limit: int = None):
|
|
@@ -1490,7 +1341,7 @@ class Client:
|
|
|
1490
1341
|
end = end if end is not None else int(time.time() * 1000)
|
|
1491
1342
|
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1492
1343
|
payload = {'mac': mac, 'start': start, 'end': end}
|
|
1493
|
-
return self.
|
|
1344
|
+
return self._request(f"/api/s/{self._site}/stat/session", method='POST', payload=payload)
|
|
1494
1345
|
|
|
1495
1346
|
def stat_sta_sessions_latest(self, mac: str, limit: int = None):
|
|
1496
1347
|
"""Fetch latest 'n' login sessions for a client (defaults to 5)."""
|
|
@@ -1505,7 +1356,7 @@ class Client:
|
|
|
1505
1356
|
end = end if end is not None else int(time.time() * 1000)
|
|
1506
1357
|
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1507
1358
|
payload = {'mac': mac, 'start': start, 'end': end}
|
|
1508
|
-
return self.
|
|
1359
|
+
return self._request(f"/api/s/{self._site}/stat/user", method='POST', payload=payload)
|
|
1509
1360
|
|
|
1510
1361
|
def stat_all_user(self, start: int = None, end: int = None):
|
|
1511
1362
|
"""
|
|
@@ -1514,7 +1365,7 @@ class Client:
|
|
|
1514
1365
|
end = end if end is not None else int(time.time() * 1000)
|
|
1515
1366
|
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1516
1367
|
payload = {'start': start, 'end': end}
|
|
1517
|
-
return self.
|
|
1368
|
+
return self._request(f"/api/s/{self._site}/stat/alluser", method='POST', payload=payload)
|
|
1518
1369
|
|
|
1519
1370
|
def stat_allusers(self, historyhours: int = 8760):
|
|
1520
1371
|
"""Fetch clients seen within the past N hours (all-time totals)."""
|
|
@@ -1529,7 +1380,7 @@ class Client:
|
|
|
1529
1380
|
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1530
1381
|
attribs = ['time'] + attribs if attribs else ['time'] + self.default_site_stats_attribs
|
|
1531
1382
|
payload = {'attrs': attribs, 'start': start, 'end': end}
|
|
1532
|
-
return self.
|
|
1383
|
+
return self._request(f"/api/s/{self._site}/stat/report/daily.site", method='POST', payload=payload)
|
|
1533
1384
|
|
|
1534
1385
|
def stat_monthly_site(self, start: int = None, end: int = None, attribs: list = None):
|
|
1535
1386
|
"""
|
|
@@ -1539,33 +1390,33 @@ class Client:
|
|
|
1539
1390
|
start = start if start is not None else end - (30 * 24 * 3600 * 1000)
|
|
1540
1391
|
attribs = ['time'] + attribs if attribs else ['time'] + self.default_site_stats_attribs
|
|
1541
1392
|
payload = {'attrs': attribs, 'start': start, 'end': end}
|
|
1542
|
-
return self.
|
|
1393
|
+
return self._request(f"/api/s/{self._site}/stat/report/monthly.site", method='POST', payload=payload)
|
|
1543
1394
|
|
|
1544
1395
|
def stat_current_user(self):
|
|
1545
1396
|
"""
|
|
1546
1397
|
Get stats for currently connected users.
|
|
1547
1398
|
"""
|
|
1548
|
-
return self.
|
|
1399
|
+
return self._request(f"/api/s/{self._site}/stat/sta")
|
|
1549
1400
|
|
|
1550
1401
|
def stat_all_users(self):
|
|
1551
1402
|
"""
|
|
1552
1403
|
Get usage stats for all known users.
|
|
1553
1404
|
"""
|
|
1554
|
-
return self.
|
|
1405
|
+
return self._request(f"/api/s/{self._site}/stat/alluser")
|
|
1555
1406
|
|
|
1556
1407
|
def stat_voucher(self, create_time: int = None):
|
|
1557
1408
|
"""
|
|
1558
1409
|
Fetch statistics about vouchers, optionally filtering by creation time
|
|
1559
1410
|
"""
|
|
1560
1411
|
payload = {'create_time': create_time} if create_time is not None else {}
|
|
1561
|
-
return self.
|
|
1412
|
+
return self._request(f"/api/s/{self._site}/stat/voucher", payload=payload)
|
|
1562
1413
|
|
|
1563
1414
|
def stat_payment(self, within: int=None):
|
|
1564
1415
|
"""
|
|
1565
1416
|
Fetch statistics about payments, optionally filtering by time window
|
|
1566
1417
|
"""
|
|
1567
1418
|
path_suffix = f"?within={within}" if within is not None else ""
|
|
1568
|
-
return self.
|
|
1419
|
+
return self._request(f"api/s/{self._site}/stat/payment{path_suffix}")
|
|
1569
1420
|
|
|
1570
1421
|
def create_hotspotop(self, name: str, x_password: str, note: str = '') -> bool:
|
|
1571
1422
|
"""Create hotspot operator user"""
|
|
@@ -1587,7 +1438,7 @@ class Client:
|
|
|
1587
1438
|
end = end if end is not None else int(time.time())
|
|
1588
1439
|
start = start if start is not None else end - (7 * 24 * 3600)
|
|
1589
1440
|
payload = {'start': start, 'end': end}
|
|
1590
|
-
return self.
|
|
1441
|
+
return self._request(f"/api/s/{self._site}/stat/authorization", payload=payload)
|
|
1591
1442
|
|
|
1592
1443
|
def stat_sessions(self, start: int = None, end: int = None, mac: str = None, type: str = 'all'):
|
|
1593
1444
|
"""
|
|
@@ -1603,7 +1454,7 @@ class Client:
|
|
|
1603
1454
|
if mac:
|
|
1604
1455
|
payload['mac'] = mac.lower()
|
|
1605
1456
|
|
|
1606
|
-
return self.
|
|
1457
|
+
return self._request(f"/api/s/{self._site}/stat/session", payload=payload)
|
|
1607
1458
|
|
|
1608
1459
|
def stat_client(self, mac: str):
|
|
1609
1460
|
"""Fetch details for a single client device."""
|
|
@@ -1676,7 +1527,7 @@ class Client:
|
|
|
1676
1527
|
Retrieve list of alarms with optional filtering payload
|
|
1677
1528
|
"""
|
|
1678
1529
|
payload = payload or {}
|
|
1679
|
-
return self.
|
|
1530
|
+
return self._request(f"/api/s/{self._site}/list/alarm", payload=payload)
|
|
1680
1531
|
|
|
1681
1532
|
def list_events(self, historyhours: int = 720, start: int = 0, limit: int = 3000):
|
|
1682
1533
|
payload = {
|
|
@@ -1686,16 +1537,16 @@ class Client:
|
|
|
1686
1537
|
'_start': start,
|
|
1687
1538
|
'_limit': limit
|
|
1688
1539
|
}
|
|
1689
|
-
return self.
|
|
1540
|
+
return self._request(f"/api/s/{self._site}/stat/event", payload=payload)
|
|
1690
1541
|
|
|
1691
1542
|
def list_tags(self):
|
|
1692
|
-
return self.
|
|
1543
|
+
return self._request(f"/api/s/{self._site}/rest/tag")
|
|
1693
1544
|
|
|
1694
1545
|
def list_dpi_stats(self):
|
|
1695
1546
|
"""
|
|
1696
1547
|
List DPI stats.
|
|
1697
1548
|
"""
|
|
1698
|
-
return self.
|
|
1549
|
+
return self._request(f"/api/s/{self._site}/stat/dpi")
|
|
1699
1550
|
|
|
1700
1551
|
def list_dpi_stats_filtered(self, type: str = 'by_cat', cat_filter: list = None):
|
|
1701
1552
|
"""
|
|
@@ -1709,11 +1560,11 @@ class Client:
|
|
|
1709
1560
|
if isinstance(cat_filter, list) and type == 'by_app':
|
|
1710
1561
|
payload['cats'] = cat_filter
|
|
1711
1562
|
|
|
1712
|
-
return self.
|
|
1563
|
+
return self._request(f"/api/s/{self._site}/stat/sitedpi", payload=payload)
|
|
1713
1564
|
|
|
1714
1565
|
def list_dpi_app_categories(self):
|
|
1715
1566
|
"""Fetch DPI application categories."""
|
|
1716
|
-
return self.fetch_results(f"/api/s/{self._site}/list/dpi/application/categories"
|
|
1567
|
+
return self.fetch_results(f"/api/s/{self._site}/list/dpi/application/categories")
|
|
1717
1568
|
|
|
1718
1569
|
def list_dpi_app(self):
|
|
1719
1570
|
"""Fetch DPI applications."""
|
|
@@ -1730,68 +1581,41 @@ class Client:
|
|
|
1730
1581
|
return self.fetch_results(f"/api/s/{self._site}/stat/ccode")
|
|
1731
1582
|
|
|
1732
1583
|
def list_radius_accounts(self):
|
|
1733
|
-
return self.
|
|
1584
|
+
return self._request(f"/api/s/{self._site}/rest/account")
|
|
1734
1585
|
|
|
1735
1586
|
def list_radius_profiles(self):
|
|
1736
|
-
"""Fetch RADIUS profiles"""
|
|
1737
|
-
return self.fetch_results(f"/api/s/{self._site}/rest/radiusprofile")
|
|
1738
|
-
|
|
1739
|
-
def create_radius_profile(self,
|
|
1740
|
-
"""
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
- accounting_enabled (bool): True to enable Radius accounting
|
|
1752
|
-
Returns:
|
|
1753
|
-
list/dict: Created profile data (includes '_id' field)
|
|
1587
|
+
"""Fetch RADIUS profiles for the current site"""
|
|
1588
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/radiusprofile", proxy_type='network')
|
|
1589
|
+
|
|
1590
|
+
def create_radius_profile(self, payload: dict) -> list:
|
|
1591
|
+
"""Create a RADIUS profile.
|
|
1592
|
+
|
|
1593
|
+
Accepted payload fields (verified against UniFi Network 10.x):
|
|
1594
|
+
name (str): Profile name
|
|
1595
|
+
use_usg_auth_server (bool): Use gateway as RADIUS server
|
|
1596
|
+
tls_enabled (bool): Enable RadSec/TLS for this profile
|
|
1597
|
+
auth_servers (list): [{ip, port, x_secret}]
|
|
1598
|
+
acct_servers (list): [{ip, port, x_secret}]
|
|
1599
|
+
accounting_enabled (bool): Enable RADIUS accounting
|
|
1600
|
+
|
|
1601
|
+
Returns list of created profile dicts (with _id).
|
|
1754
1602
|
"""
|
|
1755
1603
|
self._curl_method = 'POST'
|
|
1756
|
-
|
|
1757
|
-
self._curl_method = 'GET'
|
|
1758
|
-
return result
|
|
1759
|
-
|
|
1760
|
-
def set_radius_profile(self, profile_id:str, data:dict) -> dict | bool:
|
|
1761
|
-
"""
|
|
1762
|
-
Update an existing Radius Profile
|
|
1763
|
-
|
|
1764
|
-
Args:
|
|
1765
|
-
- profile_id (str): The '_id' of the profile to update
|
|
1766
|
-
- data (dict):
|
|
1767
|
-
- name (str): Profile display name
|
|
1768
|
-
- use_usg_auth_server (bool): False (we supply our own servers)
|
|
1769
|
-
- auth_servers (list[dict]): Authentication Servers, each with:
|
|
1770
|
-
- ip (str): Radius Server IP
|
|
1771
|
-
- port (int): Auth port (typically 1812)
|
|
1772
|
-
- x_secret (str): Shared secret
|
|
1773
|
-
- accounting_enabled (bool): True to enable Radius accounting
|
|
1774
|
-
Returns:
|
|
1775
|
-
bool/dict: Success indicator or updated profile data
|
|
1776
|
-
"""
|
|
1777
|
-
self._curl_method = 'PUT'
|
|
1778
|
-
result = self.fetch_results(f'/api/s/{self._site}/rest/radiusprofile/{profile_id}', payload=data)
|
|
1779
|
-
self._curl_method = 'GET'
|
|
1780
|
-
return result
|
|
1781
|
-
|
|
1782
|
-
def delete_radius_profile(self, profile_id:str) -> bool:
|
|
1783
|
-
"""
|
|
1784
|
-
Delete a Radius Profile
|
|
1604
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/radiusprofile", payload=payload, proxy_type='network')
|
|
1785
1605
|
|
|
1786
|
-
|
|
1787
|
-
|
|
1606
|
+
def set_radius_profile(self, profile_id: str, payload: dict) -> bool:
|
|
1607
|
+
"""Update an existing RADIUS profile by ID."""
|
|
1608
|
+
self._curl_method = "PUT"
|
|
1609
|
+
return self.fetch_results_boolean(
|
|
1610
|
+
f'/api/s/{self._site}/rest/radiusprofile/{profile_id.strip()}',
|
|
1611
|
+
payload=payload)
|
|
1788
1612
|
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
"""
|
|
1613
|
+
def delete_radius_profile(self, profile_id: str) -> bool:
|
|
1614
|
+
"""Delete a RADIUS profile by ID."""
|
|
1792
1615
|
self._curl_method = 'DELETE'
|
|
1793
|
-
result = self.
|
|
1794
|
-
|
|
1616
|
+
result = self.fetch_results_boolean(
|
|
1617
|
+
f"/api/s/{self._site}/rest/radiusprofile/{profile_id.strip()}")
|
|
1618
|
+
self._curl_method = self.DEFAULT_CURL_METHOD
|
|
1795
1619
|
return result
|
|
1796
1620
|
|
|
1797
1621
|
def create_radius_account(self, name: str, x_password: str, tunnel_type: int = None, tunnel_medium_type: int = None, vlan: str = None) -> dict:
|
|
@@ -1824,6 +1648,7 @@ class Client:
|
|
|
1824
1648
|
end: int = None,
|
|
1825
1649
|
page_number: int = 0,
|
|
1826
1650
|
page_size: int = 100,
|
|
1651
|
+
custom_payload: dict = None
|
|
1827
1652
|
) -> list:
|
|
1828
1653
|
"""Fetch system logs filtered by class and time window with pagination"""
|
|
1829
1654
|
# Determine time window
|
|
@@ -1843,8 +1668,8 @@ class Client:
|
|
|
1843
1668
|
if class_ == 'next-ai-alert':
|
|
1844
1669
|
payload['nextAiCategory'] = ['CLIENT', 'DEVICE', 'INTERNET', 'VPN']
|
|
1845
1670
|
elif class_ == 'admin-activity':
|
|
1846
|
-
payload['
|
|
1847
|
-
payload['
|
|
1671
|
+
payload['activity_keys'] = ['ACCESSED_NETWORK_WEB', 'ACCESSED_NETWORK_IOS', 'ACCESSED_NETWORK_ANDROID']
|
|
1672
|
+
payload['change_keys'] = ['CLIENT', 'DEVICE', 'HOTSPOT', 'INTERNET', 'NETWORK', 'PROFILE', 'ROUTING', 'SECURITY', 'SYSTEM', 'VPN', 'WIFI']
|
|
1848
1673
|
elif class_ == 'update-alert':
|
|
1849
1674
|
payload['systemLogDeviceTypes'] = ['GATEWAYS', 'SWITCHES', 'ACCESS_POINT', 'SMART_POWER', 'BUILDING_TO_BUILDING_BRIDGES', 'UNIFI_LTE']
|
|
1850
1675
|
elif class_ == 'client-alert':
|
|
@@ -1855,12 +1680,11 @@ class Client:
|
|
|
1855
1680
|
elif class_ == 'triggers':
|
|
1856
1681
|
payload['triggerTypes'] = ['TRAFFIC_RULE', 'TRAFFIC_ROUTE', 'FIREWALL_RULE']
|
|
1857
1682
|
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
path = f"/v2/api/site/{self._site}/system-log/{class_}"
|
|
1683
|
+
# Merge any custom payload overrides
|
|
1684
|
+
if custom_payload:
|
|
1685
|
+
payload.update(custom_payload)
|
|
1862
1686
|
|
|
1863
|
-
return self.fetch_results(
|
|
1687
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/system-log/{class_}", payload=payload)
|
|
1864
1688
|
|
|
1865
1689
|
def delete_radius_account(self, account_id: str) -> bool:
|
|
1866
1690
|
"""Delete a Radius user account"""
|
|
@@ -1869,18 +1693,19 @@ class Client:
|
|
|
1869
1693
|
self._curl_method = 'GET'
|
|
1870
1694
|
return result
|
|
1871
1695
|
|
|
1872
|
-
def
|
|
1873
|
-
|
|
1696
|
+
def list_radius_profiles_raw(self):
|
|
1697
|
+
"""Fetch RADIUS profiles (raw _request variant)"""
|
|
1698
|
+
return self._request(f"/api/s/{self._site}/rest/radiusprofile")
|
|
1874
1699
|
|
|
1875
1700
|
def list_hotspot_operators(self):
|
|
1876
|
-
return self.
|
|
1701
|
+
return self._request(f"api/s/{self._site}/rest/hotspotop")
|
|
1877
1702
|
|
|
1878
1703
|
def count_alarms(self, archived: bool = None):
|
|
1879
1704
|
"""
|
|
1880
1705
|
Count alarms; if archived=False counts only non-archived
|
|
1881
1706
|
"""
|
|
1882
1707
|
suffix = '?archived=false' if archived is False else ''
|
|
1883
|
-
return self.
|
|
1708
|
+
return self._request(f"/api/s/{self._site}/cnt/alarm{suffix}")
|
|
1884
1709
|
|
|
1885
1710
|
def archive_alarm(self, alarm_id: str = '') -> bool:
|
|
1886
1711
|
"""
|
|
@@ -1890,7 +1715,7 @@ class Client:
|
|
|
1890
1715
|
payload = {'_id': alarm_id, 'cmd': 'archive-alarm'}
|
|
1891
1716
|
else:
|
|
1892
1717
|
payload = {'cmd': 'archive-all-alarms'}
|
|
1893
|
-
self.
|
|
1718
|
+
self._request(f"/api/s/{self._site}/cmd/evtmgr", method="POST", payload=payload)
|
|
1894
1719
|
return self._last_response_code == 200
|
|
1895
1720
|
|
|
1896
1721
|
def stat_speedtest_results(self, start: int = None, end: int = None):
|
|
@@ -1904,35 +1729,38 @@ class Client:
|
|
|
1904
1729
|
'start': start,
|
|
1905
1730
|
'end': end
|
|
1906
1731
|
}
|
|
1907
|
-
return self.
|
|
1732
|
+
return self._request(f"/api/s/{self._site}/stat/report/archive.speedtest", payload=payload)
|
|
1733
|
+
|
|
1734
|
+
def list_health(self):
|
|
1735
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/health", proxy_type='network')
|
|
1908
1736
|
|
|
1909
1737
|
def stat_user_devices(self):
|
|
1910
1738
|
"""
|
|
1911
1739
|
Retrieve statistics on user devices.
|
|
1912
1740
|
"""
|
|
1913
|
-
return self.
|
|
1741
|
+
return self._request(f"/api/s/{self._site}/stat/user/devices")
|
|
1914
1742
|
|
|
1915
1743
|
def stat_sites(self):
|
|
1916
1744
|
"""
|
|
1917
1745
|
Retrieve statistics for all available sites.
|
|
1918
1746
|
"""
|
|
1919
|
-
return self.
|
|
1747
|
+
return self._request("/api/stat/sites")
|
|
1920
1748
|
|
|
1921
1749
|
def list_devices(self, macs: list[str] = []):
|
|
1922
1750
|
"""
|
|
1923
1751
|
Fetch UniFi devices, optionally filtered by MAC addresses.
|
|
1924
1752
|
"""
|
|
1925
1753
|
payload = {'macs': [mac.lower() for mac in macs]}
|
|
1926
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/device", payload=payload
|
|
1754
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/device", payload=payload)
|
|
1927
1755
|
|
|
1928
1756
|
def list_devices_basic(self):
|
|
1929
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/device-basic"
|
|
1757
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/device-basic")
|
|
1930
1758
|
|
|
1931
1759
|
def check_controller_update(self):
|
|
1932
1760
|
"""
|
|
1933
1761
|
Fetch latest known controller version info
|
|
1934
1762
|
"""
|
|
1935
|
-
return self.
|
|
1763
|
+
return self._request(f"/api/s/{self._site}/stat/fwupdate/latest-version")
|
|
1936
1764
|
|
|
1937
1765
|
def get_update_os_console(self):
|
|
1938
1766
|
"""
|
|
@@ -1940,7 +1768,7 @@ class Client:
|
|
|
1940
1768
|
"""
|
|
1941
1769
|
if not self._unifi_os:
|
|
1942
1770
|
raise NotAUnifiOsConsoleException()
|
|
1943
|
-
return self.
|
|
1771
|
+
return self._request('/api/firmware/update')
|
|
1944
1772
|
|
|
1945
1773
|
def update_os_console(self) -> bool:
|
|
1946
1774
|
"""
|
|
@@ -1949,9 +1777,166 @@ class Client:
|
|
|
1949
1777
|
if not self._unifi_os:
|
|
1950
1778
|
raise NotAUnifiOsConsoleException()
|
|
1951
1779
|
payload = {'persistFullData': True}
|
|
1952
|
-
|
|
1953
|
-
return
|
|
1780
|
+
self._request(f"/api/s/{self._site}/cmd/firmware/update", method='POST', payload=payload)
|
|
1781
|
+
return self._last_response_code == 200
|
|
1782
|
+
|
|
1783
|
+
|
|
1784
|
+
# === UniFi OS System Methods ===
|
|
1785
|
+
|
|
1786
|
+
def get_system_config(self):
|
|
1787
|
+
"""Get UniFi OS system configuration."""
|
|
1788
|
+
return self.fetch_results("/api/system", proxy_type=None)
|
|
1789
|
+
|
|
1790
|
+
def set_system_config(self, payload: dict):
|
|
1791
|
+
"""Update UniFi OS system configuration."""
|
|
1792
|
+
self._curl_method = 'PATCH'
|
|
1793
|
+
return self.fetch_results("/api/system", payload=payload, proxy_type=None)
|
|
1794
|
+
|
|
1795
|
+
def set_ssh_password(self, password: str):
|
|
1796
|
+
"""Set the SSH password for UniFi OS."""
|
|
1797
|
+
self._curl_method = 'POST'
|
|
1798
|
+
try:
|
|
1799
|
+
self.fetch_results("/api/system/ssh/setpassword", payload={'password': password}, proxy_type=None)
|
|
1800
|
+
return True
|
|
1801
|
+
except JsonDecodeException:
|
|
1802
|
+
# 204 No Content returns empty body - that's success
|
|
1803
|
+
return True
|
|
1804
|
+
except Exception:
|
|
1805
|
+
return False
|
|
1806
|
+
|
|
1807
|
+
def turn_on_ssh(self, password: str):
|
|
1808
|
+
"""Enable SSH on the UniFi controller."""
|
|
1809
|
+
result = self.set_ssh_password(password)
|
|
1810
|
+
if not result:
|
|
1811
|
+
return 'Failed to set password, try again later.'
|
|
1812
|
+
self._curl_method = 'PATCH'
|
|
1813
|
+
return self.fetch_results("/api/system", payload={'ssh': {'enabled': True}}, proxy_type=None)
|
|
1814
|
+
|
|
1815
|
+
def turn_off_ssh(self):
|
|
1816
|
+
"""Disable SSH on the UniFi controller."""
|
|
1817
|
+
self._curl_method = 'PATCH'
|
|
1818
|
+
return self.fetch_results("/api/system", payload={'ssh': {'enabled': False}}, proxy_type=None)
|
|
1819
|
+
|
|
1820
|
+
def get_notification_settings(self):
|
|
1821
|
+
"""Get UniFi OS notification settings."""
|
|
1822
|
+
return self.fetch_results("/api/notifications/settings", proxy_type=None)
|
|
1823
|
+
|
|
1824
|
+
def set_notification_settings(self, payload: dict):
|
|
1825
|
+
"""Update UniFi OS notification settings."""
|
|
1826
|
+
self._curl_method = 'PUT'
|
|
1827
|
+
return self.fetch_results("/api/notifications/settings", payload=payload, proxy_type=None)
|
|
1828
|
+
|
|
1829
|
+
# === User Management Methods ===
|
|
1830
|
+
|
|
1831
|
+
def list_site_users(self):
|
|
1832
|
+
"""Get all users/admins for the site."""
|
|
1833
|
+
return self.fetch_results("/api/v2/users", proxy_type='users')
|
|
1834
|
+
|
|
1835
|
+
def invite_user(self, email: str, role: str = 'admin', permissions: dict = None):
|
|
1836
|
+
"""Invite a user to the UniFi site."""
|
|
1837
|
+
payload = {'email': email, 'role': role}
|
|
1838
|
+
if permissions:
|
|
1839
|
+
payload['permissions'] = permissions
|
|
1840
|
+
self._curl_method = 'POST'
|
|
1841
|
+
return self.fetch_results("/api/v2/users/invite_add", payload=payload, proxy_type='users')
|
|
1842
|
+
|
|
1843
|
+
def deactivate_user(self, user_id: str):
|
|
1844
|
+
"""Deactivate a user account."""
|
|
1845
|
+
self._curl_method = 'PUT'
|
|
1846
|
+
return self.fetch_results(f"/api/v2/user/{user_id}/deactivate?isULP=1", proxy_type='users')
|
|
1847
|
+
|
|
1848
|
+
def activate_user(self, user_id: str):
|
|
1849
|
+
"""Activate a deactivated user account."""
|
|
1850
|
+
self._curl_method = 'PUT'
|
|
1851
|
+
return self.fetch_results(f"/api/v2/user/{user_id}/active?isULP=1", proxy_type='users')
|
|
1852
|
+
|
|
1853
|
+
def remove_user(self, user_id: str):
|
|
1854
|
+
"""Permanently remove a user account."""
|
|
1855
|
+
self._curl_method = 'DELETE'
|
|
1856
|
+
return self.fetch_results(f"/api/v2/user/{user_id}", proxy_type='users')
|
|
1857
|
+
|
|
1858
|
+
def create_custom_role(self, payload: dict):
|
|
1859
|
+
"""Create a custom permission role.
|
|
1860
|
+
|
|
1861
|
+
Args:
|
|
1862
|
+
payload: Role configuration with permissions
|
|
1863
|
+
|
|
1864
|
+
Returns:
|
|
1865
|
+
list: Created role data
|
|
1866
|
+
"""
|
|
1867
|
+
self._curl_method = 'POST'
|
|
1868
|
+
return self.fetch_results("/api/v2/custom_role", payload=payload, proxy_type='users')
|
|
1869
|
+
|
|
1870
|
+
def get_custom_role(self, network_permission: str, user_permission: str):
|
|
1871
|
+
"""Create a custom role payload from permission strings and submit it."""
|
|
1872
|
+
import random
|
|
1873
|
+
payload = {
|
|
1874
|
+
'is_private': True,
|
|
1875
|
+
'name': f'role_private_{random.randint(10000000, 99999999)}',
|
|
1876
|
+
'permission_resources': [],
|
|
1877
|
+
'permissions': []
|
|
1878
|
+
}
|
|
1879
|
+
if network_permission != 'none':
|
|
1880
|
+
payload['permissions'].append({'manifest_unique_key': 'network.management', 'formulas': [network_permission]})
|
|
1881
|
+
if user_permission != 'none':
|
|
1882
|
+
payload['permissions'].append({'manifest_unique_key': 'system.management.user', 'formulas': [user_permission]})
|
|
1883
|
+
self._curl_method = 'POST'
|
|
1884
|
+
return self.fetch_results("/api/v2/custom_role", payload=payload, proxy_type='users')
|
|
1885
|
+
|
|
1886
|
+
def resend_invite(self, email: str):
|
|
1887
|
+
"""Resend invitation to a user."""
|
|
1888
|
+
if not self.validate_email(email):
|
|
1889
|
+
return "Please enter a valid email"
|
|
1890
|
+
payload = {'email': email, 'is_resend': True}
|
|
1891
|
+
self._curl_method = 'POST'
|
|
1892
|
+
return self.fetch_results("/api/v2/users/invite_add", payload=payload, proxy_type='users')
|
|
1893
|
+
|
|
1894
|
+
def validate_email(self, email: str) -> bool:
|
|
1895
|
+
"""Validate email address format."""
|
|
1896
|
+
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
|
1897
|
+
return bool(re.match(pattern, email))
|
|
1898
|
+
|
|
1899
|
+
# === Additional Network Methods ===
|
|
1900
|
+
|
|
1901
|
+
def get_active_leases(self):
|
|
1902
|
+
"""Get active DHCP leases for the site."""
|
|
1903
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/active-leases")
|
|
1904
|
+
|
|
1905
|
+
def get_excluded_ips(self):
|
|
1906
|
+
"""Get excluded/reserved IPs for the site."""
|
|
1907
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/excluded-ips/")
|
|
1908
|
+
|
|
1909
|
+
def get_device_history(self, mac: str, is_client: bool, limit: int = 50):
|
|
1910
|
+
"""Fetch device activity/event history from system logs."""
|
|
1911
|
+
scope = 'CLIENTS' if is_client else 'DEVICE'
|
|
1912
|
+
self._curl_method = 'GET'
|
|
1913
|
+
return self.fetch_results(
|
|
1914
|
+
f"/v2/api/site/default/system-log/device/{mac}?mac={mac}&scope={scope}&limit={limit}",
|
|
1915
|
+
proxy_type='network'
|
|
1916
|
+
)
|
|
1917
|
+
|
|
1918
|
+
def list_firewall_rules(self):
|
|
1919
|
+
"""List all firewall rules for the site."""
|
|
1920
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/firewallrule", proxy_type='network')
|
|
1921
|
+
|
|
1922
|
+
def create_firewall_rule(self, payload: dict):
|
|
1923
|
+
"""Create a new firewall rule."""
|
|
1924
|
+
self._curl_method = 'POST'
|
|
1925
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/firewallrule", payload=payload, proxy_type='network')
|
|
1926
|
+
|
|
1927
|
+
def delete_firewall_rule(self, rule_id: str):
|
|
1928
|
+
"""Delete a firewall rule by ID."""
|
|
1929
|
+
self._curl_method = 'DELETE'
|
|
1930
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/rest/firewallrule/{rule_id}", proxy_type='network')
|
|
1954
1931
|
|
|
1932
|
+
# === UniFi Protect Methods ===
|
|
1933
|
+
|
|
1934
|
+
def get_protect_devices(self):
|
|
1935
|
+
"""Get UniFi Protect device stats."""
|
|
1936
|
+
try:
|
|
1937
|
+
return self.fetch_results("/api/devices/stat/", proxy_type='protect')
|
|
1938
|
+
except JsonDecodeException:
|
|
1939
|
+
return []
|
|
1955
1940
|
|
|
1956
1941
|
## ---------- Deprecated Methods ---------
|
|
1957
1942
|
def list_aps(self):
|
|
@@ -2049,7 +2034,7 @@ class Client:
|
|
|
2049
2034
|
return self._firmware_version
|
|
2050
2035
|
|
|
2051
2036
|
def set_firmware_version(self, version: str) -> bool:
|
|
2052
|
-
"""Manually set firmware version (e.g., from cached Odoo record)
|
|
2037
|
+
"""Manually set firmware version (e.g., from cached Odoo record).
|
|
2053
2038
|
|
|
2054
2039
|
Args:
|
|
2055
2040
|
version: 'v1' for legacy controllers, 'v2' for UniFi OS, or None to reset
|
|
@@ -2091,8 +2076,8 @@ class Client:
|
|
|
2091
2076
|
|
|
2092
2077
|
# ----- Protected Helper Methods -----
|
|
2093
2078
|
|
|
2094
|
-
def fetch_results_boolean(self, path: str, payload=None, login_required: bool = True,
|
|
2095
|
-
|
|
2079
|
+
def fetch_results_boolean(self, path: str, payload=None, login_required: bool = True, proxy_type: str = 'network', auto_fallback: bool = True) -> bool:
|
|
2080
|
+
return self.fetch_results(path, payload, boolean=True, login_required=login_required, proxy_type=proxy_type, auto_fallback=auto_fallback)
|
|
2096
2081
|
|
|
2097
2082
|
def _get_json_last_error(self) -> bool:
|
|
2098
2083
|
try:
|
|
@@ -2126,10 +2111,16 @@ class Client:
|
|
|
2126
2111
|
|
|
2127
2112
|
def generate_backup(self, days: int = -1):
|
|
2128
2113
|
"""Generate a controller backup for the past N days."""
|
|
2129
|
-
payload = {'cmd': 'backup', 'days': days}
|
|
2130
|
-
result = self.fetch_results(f"
|
|
2114
|
+
#payload = {'cmd': 'backup', 'days': days}
|
|
2115
|
+
result = self.fetch_results(f"{self._site}/api/backup/download", proxy_type=None, boolean=False)
|
|
2131
2116
|
print(f"RAW RESULT FROM FETCH_RESULTS(): {result}") if self.debug else None
|
|
2132
2117
|
return result
|
|
2118
|
+
|
|
2119
|
+
def test_generate_backup(self):
|
|
2120
|
+
sesh = self._session
|
|
2121
|
+
|
|
2122
|
+
result = sesh.get(f"{self._baseurl}/api/backup/download", verify=False)
|
|
2123
|
+
return result.content
|
|
2133
2124
|
|
|
2134
2125
|
def download_backup(self, filepath: str):
|
|
2135
2126
|
"""Download a generated backup file."""
|
|
@@ -2319,7 +2310,7 @@ class Client:
|
|
|
2319
2310
|
payload = {'led_enabled': enable}
|
|
2320
2311
|
return self.fetch_results_boolean(f"/api/s/{self._site}/set/setting/mgmt", payload=payload)
|
|
2321
2312
|
|
|
2322
|
-
def custom_api_request(self, path: str, method: str = 'GET', payload=None, return_type: str = 'array',
|
|
2313
|
+
def custom_api_request(self, path: str, method: str = 'GET', payload=None, return_type: str = 'array', proxy_type: str = 'network'):
|
|
2323
2314
|
"""Execute custom API request with optional boolean or array return."""
|
|
2324
2315
|
if method not in self.CURL_METHODS_ALLOWED:
|
|
2325
2316
|
return False
|
|
@@ -2327,10 +2318,10 @@ class Client:
|
|
|
2327
2318
|
return False
|
|
2328
2319
|
self._curl_method = method
|
|
2329
2320
|
if return_type == 'array':
|
|
2330
|
-
return self.fetch_results(path, payload,
|
|
2321
|
+
return self.fetch_results(path, payload, proxy_type=proxy_type)
|
|
2331
2322
|
if return_type == 'boolean':
|
|
2332
|
-
return self.fetch_results_boolean(path, payload,
|
|
2333
|
-
return False
|
|
2323
|
+
return self.fetch_results_boolean(path, payload, proxy_type=proxy_type)
|
|
2324
|
+
return False
|
|
2334
2325
|
|
|
2335
2326
|
def get_cookie(self) -> str:
|
|
2336
2327
|
return self._cookies
|
|
@@ -2340,9 +2331,54 @@ class Client:
|
|
|
2340
2331
|
|
|
2341
2332
|
def get_cookies_created_at(self) -> int:
|
|
2342
2333
|
return self._cookies_created_at
|
|
2334
|
+
|
|
2335
|
+
def __construct(
|
|
2336
|
+
self,
|
|
2337
|
+
user: str,
|
|
2338
|
+
password: str,
|
|
2339
|
+
baseurl: str = 'https://127.0.0.1:8443',
|
|
2340
|
+
site: str = 'default',
|
|
2341
|
+
version: str = '8.0.28',
|
|
2342
|
+
ssl_verify: bool = False,
|
|
2343
|
+
unificookie_name: str = 'unificookie'
|
|
2344
|
+
):
|
|
2345
|
+
"""
|
|
2346
|
+
PHP constructor conversion: checks and initial assignments.
|
|
2347
|
+
"""
|
|
2348
|
+
# Ensure HTTP client available
|
|
2349
|
+
self._check_curl()
|
|
2350
|
+
# Validate base URL and site
|
|
2351
|
+
self._check_base_url(baseurl)
|
|
2352
|
+
self._check_site(site)
|
|
2353
|
+
|
|
2354
|
+
# Assign core properties
|
|
2355
|
+
self._baseurl = baseurl.strip()
|
|
2356
|
+
self._site = site.strip().lower()
|
|
2357
|
+
self._user = user.strip()
|
|
2358
|
+
self._password = password.strip()
|
|
2359
|
+
self._version = version.strip()
|
|
2360
|
+
self._unificookie_name = unificookie_name.strip()
|
|
2361
|
+
|
|
2362
|
+
# SSL verification settings
|
|
2363
|
+
self._verify_ssl_cert = ssl_verify
|
|
2364
|
+
|
|
2365
|
+
def __destruct(self):
|
|
2366
|
+
"""
|
|
2367
|
+
PHP destructor: if the unificookie is set in session, skip logout; otherwise logout if logged in.
|
|
2368
|
+
"""
|
|
2369
|
+
# If the unificookie is present in session cookies, skip logout
|
|
2370
|
+
if self._unificookie_name in self._session.cookies.get_dict():
|
|
2371
|
+
return
|
|
2372
|
+
|
|
2373
|
+
# Logout if still logged in
|
|
2374
|
+
if getattr(self, '_is_loggedin', False):
|
|
2375
|
+
try:
|
|
2376
|
+
self.logout()
|
|
2377
|
+
except Exception:
|
|
2378
|
+
pass
|
|
2343
2379
|
|
|
2344
2380
|
def list_firewallgroups(self, group_id: str = ''):
|
|
2345
|
-
return self.fetch_results(f"/api/s/{self._site}/rest/firewallgroup/{group_id.strip()}"
|
|
2381
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/firewallgroup/{group_id.strip()}")
|
|
2346
2382
|
|
|
2347
2383
|
def create_firewallgroup(self, group_name: str, group_type: str, group_members: list = []) -> bool:
|
|
2348
2384
|
"""Create a new firewall group"""
|
|
@@ -2354,7 +2390,11 @@ class Client:
|
|
|
2354
2390
|
'group_type': group_type,
|
|
2355
2391
|
'group_members': group_members
|
|
2356
2392
|
}
|
|
2357
|
-
return self.
|
|
2393
|
+
return self._request(
|
|
2394
|
+
f"/api/s/{self._site}/rest/firewallgroup",
|
|
2395
|
+
method='POST',
|
|
2396
|
+
payload=payload
|
|
2397
|
+
)
|
|
2358
2398
|
|
|
2359
2399
|
def edit_firewallgroup(self, group_id: str, site_id: str, group_name: str, group_type: str, group_members: list = []) -> bool:
|
|
2360
2400
|
"""Edit an existing firewall group"""
|
|
@@ -2369,11 +2409,10 @@ class Client:
|
|
|
2369
2409
|
'group_members': group_members,
|
|
2370
2410
|
'site_id': site_id
|
|
2371
2411
|
}
|
|
2372
|
-
self.
|
|
2373
|
-
return self.fetch_results(
|
|
2412
|
+
return self._request(
|
|
2374
2413
|
f"/api/s/{self._site}/rest/firewallgroup/{group_id.strip()}",
|
|
2375
|
-
|
|
2376
|
-
|
|
2414
|
+
method='PUT',
|
|
2415
|
+
payload=payload
|
|
2377
2416
|
)
|
|
2378
2417
|
|
|
2379
2418
|
def delete_firewallgroup(self, group_id: str) -> bool:
|
|
@@ -2382,7 +2421,7 @@ class Client:
|
|
|
2382
2421
|
self._curl_method = "GET"
|
|
2383
2422
|
|
|
2384
2423
|
def list_firewallrules(self):
|
|
2385
|
-
return self.
|
|
2424
|
+
return self._request(f"/api/s/{self._site}/rest/firewallrule")
|
|
2386
2425
|
|
|
2387
2426
|
def list_routing(self, route_id: str = ''):
|
|
2388
2427
|
return self.fetch_results(f"/api/s/{self._site}/rest/routing/{route_id.strip()}")
|
|
@@ -2562,7 +2601,7 @@ class Client:
|
|
|
2562
2601
|
def fetch_results(
|
|
2563
2602
|
self,
|
|
2564
2603
|
path: str,
|
|
2565
|
-
payload
|
|
2604
|
+
payload=None,
|
|
2566
2605
|
boolean: bool = False,
|
|
2567
2606
|
login_required: bool = False,
|
|
2568
2607
|
proxy_type: str = 'network',
|
|
@@ -2582,9 +2621,6 @@ class Client:
|
|
|
2582
2621
|
- None: No prefix, direct /api/ path (v2 only)
|
|
2583
2622
|
auto_fallback: If True, automatically fallback from v2 to v1 on JSON decode error
|
|
2584
2623
|
(only applies when proxy_type='network')
|
|
2585
|
-
|
|
2586
|
-
Returns:
|
|
2587
|
-
API response data, or boolean if boolean=True
|
|
2588
2624
|
"""
|
|
2589
2625
|
if login_required and not self._is_loggedin:
|
|
2590
2626
|
raise LoginRequiredException()
|
|
@@ -2607,7 +2643,6 @@ class Client:
|
|
|
2607
2643
|
print("Fetched response:", response) if self.debug else None
|
|
2608
2644
|
|
|
2609
2645
|
# Cache successful firmware version (only if not already cached)
|
|
2610
|
-
# If any proxy path works, we're on v2 (UniFi OS)
|
|
2611
2646
|
if self._firmware_version is None and used_proxy_type is not None:
|
|
2612
2647
|
self._firmware_version = 'v2'
|
|
2613
2648
|
if self.debug:
|
|
@@ -2625,23 +2660,20 @@ class Client:
|
|
|
2625
2660
|
return True
|
|
2626
2661
|
elif response['meta'].get('rc') == 'error':
|
|
2627
2662
|
self._last_error_message = 'An unknown error was returned by the controller'
|
|
2628
|
-
raise
|
|
2663
|
+
raise UnifiResponseError(f"Error message: {self._last_error_message} - {response}")
|
|
2629
2664
|
|
|
2630
2665
|
if path.startswith('/v2/api/'):
|
|
2631
2666
|
if 'errorCode' in response:
|
|
2632
2667
|
self._last_error_message = 'An unknown error was returned by an API v2 endpoint'
|
|
2633
|
-
raise
|
|
2668
|
+
raise UnifiResponseError(f"Error code: {response['errorCode']}, message: {self._last_error_message}")
|
|
2634
2669
|
return response
|
|
2635
2670
|
|
|
2636
2671
|
# Proxy API response (users, protect, etc.)
|
|
2637
|
-
# These have code: 1 (positive) for success, negative codes for errors
|
|
2638
2672
|
if used_proxy_type is not None:
|
|
2639
2673
|
if 'code' in response:
|
|
2640
2674
|
if response['code'] < 0:
|
|
2641
|
-
# Negative code is an error
|
|
2642
2675
|
self._last_error_message = response.get('msg', response.get('message', 'API error'))
|
|
2643
|
-
raise
|
|
2644
|
-
# Positive code (1) means success - return data
|
|
2676
|
+
raise UnifiHTTPError(f"Error code: {response['code']}, message: {self._last_error_message}", response['code'])
|
|
2645
2677
|
if 'data' in response:
|
|
2646
2678
|
return response['data'] if not boolean else True
|
|
2647
2679
|
return response if not boolean else True
|
|
@@ -2651,7 +2683,7 @@ class Client:
|
|
|
2651
2683
|
if path.startswith('/api/') and used_proxy_type is None:
|
|
2652
2684
|
if 'code' in response:
|
|
2653
2685
|
self._last_error_message = response.get('message', 'An unknown error was returned by a UniFi OS endpoint.')
|
|
2654
|
-
raise
|
|
2686
|
+
raise UnifiHTTPError(f"Error code: {response['code']}, message: {self._last_error_message}")
|
|
2655
2687
|
if not boolean:
|
|
2656
2688
|
return [response]
|
|
2657
2689
|
return True
|
|
@@ -2668,7 +2700,6 @@ class Client:
|
|
|
2668
2700
|
proxy_type=None, # v1 uses no proxy prefix
|
|
2669
2701
|
auto_fallback=False # Don't recurse again
|
|
2670
2702
|
)
|
|
2671
|
-
# Re-raise if fallback not applicable or already tried
|
|
2672
2703
|
raise JsonDecodeException(f"Invalid JSON response from controller: {e}")
|
|
2673
2704
|
|
|
2674
2705
|
def fetch_results_boolean(
|
|
@@ -2731,17 +2762,6 @@ class Client:
|
|
|
2731
2762
|
if self._unifi_os and proxy_type:
|
|
2732
2763
|
url = f"{self._baseurl}/proxy/{proxy_type}{path}"
|
|
2733
2764
|
|
|
2734
|
-
# 3) build curl_options dict
|
|
2735
|
-
"""
|
|
2736
|
-
curl_options = {
|
|
2737
|
-
'method': self._curl_method,
|
|
2738
|
-
'url': url,
|
|
2739
|
-
'headers': None, # filled in below
|
|
2740
|
-
'timeout': 30,
|
|
2741
|
-
'verify': self._verify_ssl_cert,
|
|
2742
|
-
}
|
|
2743
|
-
"""
|
|
2744
|
-
|
|
2745
2765
|
opts = self.get_curl_handle()
|
|
2746
2766
|
|
|
2747
2767
|
opts.update({
|
|
@@ -2757,11 +2777,9 @@ class Client:
|
|
|
2757
2777
|
opts['data'] = json_payload
|
|
2758
2778
|
|
|
2759
2779
|
# force POST if GET or DELETE
|
|
2760
|
-
|
|
2761
2780
|
if self._curl_method in ('GET', 'DELETE'):
|
|
2762
2781
|
self._curl_method = 'POST'
|
|
2763
2782
|
opts['method'] = 'POST'
|
|
2764
|
-
|
|
2765
2783
|
|
|
2766
2784
|
# 5) set custom method flags
|
|
2767
2785
|
if self._curl_method == 'POST':
|
|
@@ -2796,7 +2814,7 @@ class Client:
|
|
|
2796
2814
|
# clear stored cookie/token
|
|
2797
2815
|
self.cookies = ''
|
|
2798
2816
|
self.cookies_created_at = 0
|
|
2799
|
-
self.
|
|
2817
|
+
self._is_loggedin = False
|
|
2800
2818
|
self._exec_retries += 1
|
|
2801
2819
|
|
|
2802
2820
|
if self._session:
|
|
@@ -2810,7 +2828,21 @@ class Client:
|
|
|
2810
2828
|
raise LoginFailedException('Cookie/Token expired and re-login failed.')
|
|
2811
2829
|
raise LoginFailedException('Login failed, check credentials.')
|
|
2812
2830
|
|
|
2813
|
-
# 10)
|
|
2831
|
+
# 10) reject terminal HTTP errors before they reach JSON parsing
|
|
2832
|
+
# Only catch 429 (rate limit) and 5xx (server errors) here.
|
|
2833
|
+
# Other 4xx codes (like 404) must pass through so that the
|
|
2834
|
+
# v2→v1 firmware detection fallback in fetch_results can work.
|
|
2835
|
+
if http_code == 429 or http_code >= 500:
|
|
2836
|
+
body_preview = resp.text[:200] if resp.text else ''
|
|
2837
|
+
self._curl_method = self.DEFAULT_CURL_METHOD
|
|
2838
|
+
self._exec_retries = 0
|
|
2839
|
+
raise CurlGeneralErrorException(
|
|
2840
|
+
f"HTTP {http_code}: {body_preview}",
|
|
2841
|
+
http_code,
|
|
2842
|
+
body_preview,
|
|
2843
|
+
)
|
|
2844
|
+
|
|
2845
|
+
# 11) debug dump
|
|
2814
2846
|
if self.debug:
|
|
2815
2847
|
print("\n---------cURL INFO-----------")
|
|
2816
2848
|
print("Options:", opts)
|
|
@@ -2821,7 +2853,7 @@ class Client:
|
|
|
2821
2853
|
print(self._curl_method)
|
|
2822
2854
|
print("-----------------------------\n")
|
|
2823
2855
|
|
|
2824
|
-
#
|
|
2856
|
+
# 12) reset method and retry count
|
|
2825
2857
|
self._curl_method = self.DEFAULT_CURL_METHOD
|
|
2826
2858
|
self._exec_retries = 0
|
|
2827
2859
|
|
|
@@ -2921,131 +2953,121 @@ class Client:
|
|
|
2921
2953
|
for header in self.curl_headers:
|
|
2922
2954
|
if header.lower().find('x-csrf-token:') == -1:
|
|
2923
2955
|
filtered.append(header)
|
|
2924
|
-
self.
|
|
2956
|
+
self.curl_headers = filtered
|
|
2925
2957
|
|
|
2926
2958
|
# 8) Append the new header, using only ASCII
|
|
2927
|
-
self.
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
"""
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2959
|
+
self.curl_headers.append('x-csrf-token: %s' % csrf_token)
|
|
2960
|
+
|
|
2961
|
+
|
|
2962
|
+
|
|
2963
|
+
def restore(client:Client, filepath:str):
|
|
2964
|
+
sesh = client._session
|
|
2965
|
+
candidates = [
|
|
2966
|
+
("backup", "/api/system/backup/restore"),
|
|
2967
|
+
("file", "/api/system/backup/restore"),
|
|
2968
|
+
("backup", "/api/v2/system/backup/restore"),
|
|
2969
|
+
("file", "/api/v2/system/backup/restore"),
|
|
2970
|
+
]
|
|
2971
|
+
for field, path in candidates:
|
|
2972
|
+
with open(filepath, 'rb') as f:
|
|
2973
|
+
r = sesh.post(f"https://47.22.145.45{path}", files={field: f}, verify=False)
|
|
2974
|
+
print(f"{path} [{field}] → {r.status_code}: {r.text[:120]}")
|
|
2975
|
+
return None
|
|
2976
|
+
|
|
2977
|
+
|
|
2978
|
+
def get_users(client:Client):
|
|
2979
|
+
"""Grabs all the users that the site manages"""
|
|
2980
|
+
try:
|
|
2981
|
+
client.login()
|
|
2982
|
+
except UnifiAuthError:
|
|
2983
|
+
return {'msg': 'error', 'error': 'Rate limited - try again later', 'code': 429}
|
|
2984
|
+
|
|
2985
|
+
sesh = client._session
|
|
2986
|
+
url = f'{client._baseurl}/proxy/users/api/v2/users'
|
|
2987
|
+
result = sesh.get(url, verify=False, timeout=30)
|
|
2988
|
+
return result.json()
|
|
2989
|
+
|
|
2990
|
+
def create_new_user(client:Client, first_name: str, last_name: str, user_email: str, is_admin: bool = False,
|
|
2991
|
+
local_account: bool = False, username: str = '', password: str = '',
|
|
2992
|
+
network_permission: str = '', user_permission: str = ''):
|
|
2993
|
+
"""
|
|
2994
|
+
Creates new users/admins
|
|
2951
2995
|
|
|
2952
|
-
|
|
2953
|
-
"""Enable SSH on the UniFi controller.
|
|
2996
|
+
======PARAMS=======
|
|
2954
2997
|
|
|
2955
|
-
|
|
2956
|
-
|
|
2998
|
+
is_admin: Boolean - determines if an account is an admin
|
|
2999
|
+
local_account: Boolean - an admin account thats only limited to this local site
|
|
3000
|
+
username: String - only set this if you're using a local account, will be used for the user to log in
|
|
3001
|
+
password: String - password of the local account
|
|
2957
3002
|
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
if not result:
|
|
2963
|
-
return 'Failed to set password, try again later.'
|
|
3003
|
+
permission: String - The permissions of an admin/local account
|
|
3004
|
+
Available permissions
|
|
3005
|
+
Network - 'admin', 'hotspotoperator', 'readonly', 'none'
|
|
3006
|
+
User Management - 'admin', 'readonly', 'none'
|
|
2964
3007
|
|
|
2965
|
-
|
|
2966
|
-
|
|
3008
|
+
"""
|
|
3009
|
+
try:
|
|
3010
|
+
client.login()
|
|
3011
|
+
except UnifiAuthError:
|
|
3012
|
+
return {'msg': 'error', 'error': 'Rate limited - try again later', 'code': 429}
|
|
2967
3013
|
|
|
2968
|
-
|
|
2969
|
-
|
|
3014
|
+
if local_account and not is_admin:
|
|
3015
|
+
return {'msg': 'error', 'error': 'Local accounts must also be admin accounts'}
|
|
2970
3016
|
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
3017
|
+
valid_permissions = [
|
|
3018
|
+
'admin',
|
|
3019
|
+
'hotspotoperator',
|
|
3020
|
+
'readonly',
|
|
3021
|
+
'none'
|
|
3022
|
+
]
|
|
2976
3023
|
|
|
2977
|
-
|
|
2978
|
-
# Utility Methods
|
|
2979
|
-
# =========================================================================
|
|
3024
|
+
sesh = client._session
|
|
2980
3025
|
|
|
2981
|
-
|
|
2982
|
-
"""Get UniFi Protect device stats.
|
|
3026
|
+
url = f'{client._baseurl}/proxy/users/api/v2/user'
|
|
2983
3027
|
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
return self.fetch_results("/api/devices/stat/", proxy_type='protect')
|
|
2989
|
-
except JsonDecodeException:
|
|
2990
|
-
# UniFi Protect not installed returns empty/invalid response
|
|
2991
|
-
return []
|
|
3028
|
+
payload = {
|
|
3029
|
+
'first_name': first_name,
|
|
3030
|
+
'last_name': last_name,
|
|
3031
|
+
}
|
|
2992
3032
|
|
|
2993
|
-
|
|
2994
|
-
|
|
3033
|
+
if user_email:
|
|
3034
|
+
payload['user_email'] = user_email
|
|
2995
3035
|
|
|
2996
|
-
|
|
2997
|
-
|
|
3036
|
+
if is_admin:
|
|
3037
|
+
net_perm = network_permission.lower().strip()
|
|
3038
|
+
user_perm = user_permission.lower().strip()
|
|
2998
3039
|
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
"""
|
|
3002
|
-
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
|
3003
|
-
return bool(re.match(pattern, email))
|
|
3040
|
+
if net_perm not in valid_permissions:
|
|
3041
|
+
return {'msg': 'error', 'error': 'Invalid network permission. Must be one of: admin, hotspotoperator, readonly, none'}
|
|
3004
3042
|
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
# =========================================================================
|
|
3043
|
+
if user_perm not in valid_permissions:
|
|
3044
|
+
return {'msg': 'error', 'error': 'Invalid user permission. Must be one of: admin, readonly, none'}
|
|
3008
3045
|
|
|
3009
|
-
|
|
3010
|
-
|
|
3046
|
+
if user_perm == 'none' and net_perm == 'none':
|
|
3047
|
+
return {'msg': 'error', 'error': 'Admin users must have at least one permission'}
|
|
3011
3048
|
|
|
3012
|
-
|
|
3013
|
-
Use create_custom_role() if you need to pass a raw payload.
|
|
3049
|
+
role_id = ''
|
|
3014
3050
|
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
import random
|
|
3023
|
-
payload = {
|
|
3024
|
-
'is_private': True,
|
|
3025
|
-
'name': f'role_private_{random.randint(10000000, 99999999)}',
|
|
3026
|
-
'permission_resources': [],
|
|
3027
|
-
'permissions': []
|
|
3028
|
-
}
|
|
3029
|
-
if network_permission != 'none':
|
|
3030
|
-
payload['permissions'].append({'manifest_unique_key': 'network.management', 'formulas': [network_permission]})
|
|
3031
|
-
if user_permission != 'none':
|
|
3032
|
-
payload['permissions'].append({'manifest_unique_key': 'system.management.user', 'formulas': [user_permission]})
|
|
3033
|
-
|
|
3034
|
-
self._curl_method = 'POST'
|
|
3035
|
-
return self.fetch_results("/api/v2/custom_role", payload=payload, proxy_type='users')
|
|
3051
|
+
# Grab the role id from the helper script
|
|
3052
|
+
role = client.get_custom_role(net_perm, user_perm)
|
|
3053
|
+
print(role)
|
|
3054
|
+
if role and role.get('msg') != 'error':
|
|
3055
|
+
role_id = role['unique_id']
|
|
3056
|
+
else:
|
|
3057
|
+
return {'msg': 'error', 'error': 'Unable to fetch role data from UniFi'}
|
|
3036
3058
|
|
|
3037
|
-
|
|
3038
|
-
|
|
3059
|
+
payload.update({
|
|
3060
|
+
'email': user_email,
|
|
3061
|
+
'role_id': role_id
|
|
3062
|
+
})
|
|
3039
3063
|
|
|
3040
|
-
|
|
3041
|
-
|
|
3064
|
+
if local_account:
|
|
3065
|
+
payload.update({
|
|
3066
|
+
'username': username,
|
|
3067
|
+
'password': password,
|
|
3068
|
+
'only_local_account': True
|
|
3069
|
+
})
|
|
3042
3070
|
|
|
3043
|
-
|
|
3044
|
-
API response data, or error string iwf invalid email.
|
|
3045
|
-
"""
|
|
3046
|
-
if not self.validate_email(email):
|
|
3047
|
-
return "Please enter a valid email"
|
|
3071
|
+
results = sesh.post(url, verify=False, json=payload)
|
|
3048
3072
|
|
|
3049
|
-
|
|
3050
|
-
self._curl_method = 'POST'
|
|
3051
|
-
return self.fetch_results("/api/v2/users/invite_add", payload=payload, proxy_type='users')
|
|
3073
|
+
return results.json()
|