Python-Unifi-Client 1.0.0__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.
|
@@ -0,0 +1,2607 @@
|
|
|
1
|
+
from http import cookies
|
|
2
|
+
from sys import exception
|
|
3
|
+
import requests
|
|
4
|
+
from requests.exceptions import Timeout, RequestException
|
|
5
|
+
import time
|
|
6
|
+
import re
|
|
7
|
+
import json
|
|
8
|
+
from urllib.parse import urlencode, urlparse
|
|
9
|
+
import http.client as http_client
|
|
10
|
+
import logging
|
|
11
|
+
import base64
|
|
12
|
+
|
|
13
|
+
logging.basicConfig(level=logging.DEBUG)
|
|
14
|
+
logging.getLogger('requests.packages.urllib3').setLevel(logging.DEBUG)
|
|
15
|
+
http_client.HTTPConnection.debuglevel = 1
|
|
16
|
+
|
|
17
|
+
# Custom exceptions mirroring PHP equivalents
|
|
18
|
+
class CurlExtensionNotLoadedException(Exception):
|
|
19
|
+
def __init__(self):
|
|
20
|
+
super().__init__("The Python requests library (or equivalent HTTP client) is not available. Please install it before proceeding!")
|
|
21
|
+
class CurlGeneralErrorException(Exception):
|
|
22
|
+
"""
|
|
23
|
+
Exception raised for general CURL-related errors.
|
|
24
|
+
|
|
25
|
+
Attributes:
|
|
26
|
+
http_response_code: The HTTP response code returned by the request.
|
|
27
|
+
curl_getinfo_results: The result of curl_getinfo (or equivalent diagnostics).
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, message: str, http_response_code, curl_getinfo_results):
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self._http_response_code = http_response_code
|
|
33
|
+
self._curl_getinfo_results = curl_getinfo_results
|
|
34
|
+
|
|
35
|
+
def get_http_reponse_code(self):
|
|
36
|
+
return self._http_response_code
|
|
37
|
+
|
|
38
|
+
def get_curl_getinfo_results(self):
|
|
39
|
+
return self._curl_getinfo_results
|
|
40
|
+
class CurlTimeoutException(Exception):
|
|
41
|
+
"""
|
|
42
|
+
Exception raised for cURL timeout errors.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
http_response_code: The HTTP response code returned by the request.
|
|
46
|
+
curl_getinfo_results: The result of curl_getinfo (or equivalent diagnostics).
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, message: str, http_response_code, curl_getinfo_results):
|
|
50
|
+
super().__init__(message)
|
|
51
|
+
self._http_response_code = http_response_code
|
|
52
|
+
self._curl_getinfo_results = curl_getinfo_results
|
|
53
|
+
|
|
54
|
+
def get_http_response_code(self):
|
|
55
|
+
return self._http_response_code
|
|
56
|
+
|
|
57
|
+
def get_curl_getinfo_results(self):
|
|
58
|
+
return self._curl_getinfo_results
|
|
59
|
+
class EmailInvalidException(Exception):
|
|
60
|
+
def __init__(self):
|
|
61
|
+
super().__init__("Invalid email address provided")
|
|
62
|
+
class InvalidBaseUrlException(Exception):
|
|
63
|
+
def __init__(self):
|
|
64
|
+
super().__init__("The base URL provided is invalid.")
|
|
65
|
+
class InvalidCurlMethodException(Exception):
|
|
66
|
+
def __init__(self):
|
|
67
|
+
super().__init__("Invalid cURL method provided")
|
|
68
|
+
class InvalidSiteNameException(Exception):
|
|
69
|
+
def __init__(self):
|
|
70
|
+
super().__init__("Invalid site name provided")
|
|
71
|
+
class JsonDecodeException(Exception): pass
|
|
72
|
+
class LoginFailedException(Exception): pass
|
|
73
|
+
class LoginRequiredException(Exception): pass
|
|
74
|
+
class MethodDeprecatedException(Exception): pass
|
|
75
|
+
class NotAUnifiOsConsoleException(Exception):
|
|
76
|
+
def __init__(self):
|
|
77
|
+
super().__init__("This is not a Unifi OS console.")
|
|
78
|
+
|
|
79
|
+
class Client:
|
|
80
|
+
CLASS_VERSION = '2.0.5'
|
|
81
|
+
CURL_METHODS_ALLOWED = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']
|
|
82
|
+
DEFAULT_CURL_METHOD = 'GET'
|
|
83
|
+
|
|
84
|
+
def __init__(self, user, password, baseurl='https://32.218.193.188', site='default', version='8.0.28', ssl_verify=False, unificookie_name='unificookie'):
|
|
85
|
+
# Initial setup mirrors PHP constructor
|
|
86
|
+
self._check_curl()
|
|
87
|
+
self._check_base_url(baseurl)
|
|
88
|
+
self._check_site(site)
|
|
89
|
+
|
|
90
|
+
self._user = user.strip()
|
|
91
|
+
self._password = password.strip()
|
|
92
|
+
self._baseurl = baseurl.strip()
|
|
93
|
+
self._site = site.strip().lower()
|
|
94
|
+
self._version = version.strip()
|
|
95
|
+
self._unificookie_name = unificookie_name.strip()
|
|
96
|
+
|
|
97
|
+
self._timeout = 5
|
|
98
|
+
|
|
99
|
+
self._verify_ssl_cert = ssl_verify
|
|
100
|
+
self._http_version = None
|
|
101
|
+
self._curl_method = self.DEFAULT_CURL_METHOD
|
|
102
|
+
self._request_timeout = 30
|
|
103
|
+
self._connect_timeout = 10
|
|
104
|
+
self._is_loggedin = False
|
|
105
|
+
self._unifi_os = False
|
|
106
|
+
self._session = requests.Session()
|
|
107
|
+
self._last_response_code = None
|
|
108
|
+
self._last_error_message = ''
|
|
109
|
+
self._last_results_raw = None
|
|
110
|
+
self._cookies_created_at = 0
|
|
111
|
+
self._exec_retries = 0
|
|
112
|
+
|
|
113
|
+
self._curl_headers = {
|
|
114
|
+
'Accept': 'application/json',
|
|
115
|
+
'Content-Type': 'application/json',
|
|
116
|
+
'Expect': ''
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
def _check_curl(self):
|
|
120
|
+
if not hasattr(requests, 'Session'):
|
|
121
|
+
raise CurlExtensionNotLoadedException("requests library is not functioning correctly")
|
|
122
|
+
|
|
123
|
+
def _check_base_url(self, baseurl):
|
|
124
|
+
if not baseurl.startswith('https://'):
|
|
125
|
+
raise InvalidBaseUrlException("Base URL must start with 'https://'")
|
|
126
|
+
|
|
127
|
+
def _check_site(self, site):
|
|
128
|
+
if not site or '/' in site:
|
|
129
|
+
raise InvalidSiteNameException("Invalid site name")
|
|
130
|
+
|
|
131
|
+
def update_unificookie(self) -> bool:
|
|
132
|
+
"""
|
|
133
|
+
Load stored cookie from session store.
|
|
134
|
+
"""
|
|
135
|
+
store = getattr(self, '_session_store', {})
|
|
136
|
+
cookie = store.get(self._unificookie_name)
|
|
137
|
+
if cookie:
|
|
138
|
+
self._cookies = cookie
|
|
139
|
+
self._cookies_created_at = int(time.time())
|
|
140
|
+
if 'TOKEN' in cookie:
|
|
141
|
+
self._unifi_os = True
|
|
142
|
+
return True
|
|
143
|
+
return False
|
|
144
|
+
|
|
145
|
+
def login(self) -> bool:
|
|
146
|
+
# Skip if already logged in via valid cookie
|
|
147
|
+
self._verify_ssl_cert = False
|
|
148
|
+
|
|
149
|
+
if self.update_unificookie():
|
|
150
|
+
self._is_loggedin = True
|
|
151
|
+
|
|
152
|
+
if self._is_loggedin:
|
|
153
|
+
return True
|
|
154
|
+
|
|
155
|
+
# 1) Prepare GET curl_options to detect controller type
|
|
156
|
+
get_options = {
|
|
157
|
+
'method': 'GET',
|
|
158
|
+
'url': f"{self._baseurl}/",
|
|
159
|
+
'headers': self._curl_headers,
|
|
160
|
+
'timeout': (self.get_connection_timeout(), self.get_curl_request_timeout()),
|
|
161
|
+
'verify': self._verify_ssl_cert
|
|
162
|
+
}
|
|
163
|
+
try:
|
|
164
|
+
resp = self._session.request(**get_options)
|
|
165
|
+
except Timeout as e:
|
|
166
|
+
raise CurlTimeoutException(str(e), None, None)
|
|
167
|
+
except RequestException as e:
|
|
168
|
+
raise CurlGeneralErrorException(str(e), None, None)
|
|
169
|
+
|
|
170
|
+
http_code = resp.status_code
|
|
171
|
+
|
|
172
|
+
# 2) Build POST curl_options for actual login
|
|
173
|
+
post_url = f"{self._baseurl}/api/login"
|
|
174
|
+
if http_code == 200:
|
|
175
|
+
self._unifi_os = True
|
|
176
|
+
post_url = f"{self._baseurl}/api/auth/login"
|
|
177
|
+
|
|
178
|
+
post_options = {
|
|
179
|
+
'method': 'POST',
|
|
180
|
+
'url': post_url,
|
|
181
|
+
'headers': {
|
|
182
|
+
**self._curl_headers,
|
|
183
|
+
'Referer': f"{self._baseurl}/login",
|
|
184
|
+
'Content-Type': 'application/json'
|
|
185
|
+
},
|
|
186
|
+
'data': json.dumps({
|
|
187
|
+
'username': self._user,
|
|
188
|
+
'password': self._password
|
|
189
|
+
}),
|
|
190
|
+
'timeout': (self.get_connection_timeout(), self.get_curl_request_timeout()),
|
|
191
|
+
'verify': self._verify_ssl_cert
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
try:
|
|
195
|
+
resp2 = self._session.request(**post_options)
|
|
196
|
+
except Timeout as e:
|
|
197
|
+
raise CurlTimeoutException(str(e), None, None)
|
|
198
|
+
except RequestException as e:
|
|
199
|
+
raise CurlGeneralErrorException(str(e), None, None)
|
|
200
|
+
|
|
201
|
+
if self.get_debug:
|
|
202
|
+
print("\n-----------LOGIN-------------")
|
|
203
|
+
print("GET Options:", get_options)
|
|
204
|
+
print("POST Options:", post_options)
|
|
205
|
+
print("Status Code:", resp2.status_code)
|
|
206
|
+
print("Response Body:", resp2.text)
|
|
207
|
+
#print("-----------------------------\n")
|
|
208
|
+
|
|
209
|
+
if resp2.status_code == 200:
|
|
210
|
+
token = resp2.headers.get('x-updated-csrf-token') or resp2.headers.get('X-Csrf-Token')
|
|
211
|
+
if token:
|
|
212
|
+
self._session.headers.update({'x-csrf-token': token,
|
|
213
|
+
'Referer': f"{self._baseurl}/login"})
|
|
214
|
+
self._is_loggedin = True
|
|
215
|
+
return True
|
|
216
|
+
|
|
217
|
+
raise LoginFailedException(f"HTTP response: {resp2.status_code}")
|
|
218
|
+
|
|
219
|
+
def logout(self) -> bool:
|
|
220
|
+
"""
|
|
221
|
+
Log out of the UniFi Controller.
|
|
222
|
+
"""
|
|
223
|
+
opts = self.get_curl_handle()
|
|
224
|
+
logout_path = "/logout"
|
|
225
|
+
|
|
226
|
+
# UniFi OS-specific handling
|
|
227
|
+
if self._unifi_os:
|
|
228
|
+
logout_path = "/api/auth/logout"
|
|
229
|
+
opts['method'] = 'POST'
|
|
230
|
+
self.create_x_csrf_token_header()
|
|
231
|
+
|
|
232
|
+
# Always POST with headers
|
|
233
|
+
opts.update({
|
|
234
|
+
'url': f"{self._baseurl}{logout_path}",
|
|
235
|
+
'method': 'POST',
|
|
236
|
+
'headers': self._curl_headers,
|
|
237
|
+
'verify': False
|
|
238
|
+
})
|
|
239
|
+
|
|
240
|
+
# Perform the request
|
|
241
|
+
try:
|
|
242
|
+
resp = self._session.request(**opts)
|
|
243
|
+
except Timeout as e:
|
|
244
|
+
raise CurlTimeoutException(str(e), None, None)
|
|
245
|
+
except RequestException as e:
|
|
246
|
+
raise CurlGeneralErrorException(str(e), None, None)
|
|
247
|
+
|
|
248
|
+
# Cleanup state
|
|
249
|
+
self._is_loggedin = False
|
|
250
|
+
self._cookies = ''
|
|
251
|
+
self._cookies_created_at = 0
|
|
252
|
+
|
|
253
|
+
return True
|
|
254
|
+
|
|
255
|
+
# === API Endpoint Methods ===
|
|
256
|
+
# The following methods are directly converted from the PHP class to Python, preserving functionality and parameters.
|
|
257
|
+
|
|
258
|
+
def get_site_stats(self):
|
|
259
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/sysinfo")
|
|
260
|
+
|
|
261
|
+
def get_clients(self):
|
|
262
|
+
return self._request(f"/api/s/{self._site}/stat/sta")
|
|
263
|
+
|
|
264
|
+
def block_client(self, mac):
|
|
265
|
+
return self._request(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload={'cmd': 'block-sta', 'mac': mac})
|
|
266
|
+
|
|
267
|
+
def unblock_client(self, mac):
|
|
268
|
+
return self._request(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload={'cmd': 'unblock-sta', 'mac': mac})
|
|
269
|
+
|
|
270
|
+
def reconnect_client(self, mac):
|
|
271
|
+
return self._request(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload={'cmd': 'kick-sta', 'mac': mac})
|
|
272
|
+
|
|
273
|
+
def authorize_guest(self, mac, minutes, up=None, down=None, megabytes=None, ap_mac=None):
|
|
274
|
+
payload = {
|
|
275
|
+
'cmd': 'authorize-guest',
|
|
276
|
+
'mac': mac.lower(),
|
|
277
|
+
'minutes': minutes
|
|
278
|
+
}
|
|
279
|
+
if up is not None: payload['up'] = up
|
|
280
|
+
if down is not None: payload['down'] = down
|
|
281
|
+
if megabytes is not None: payload['bytes'] = megabytes
|
|
282
|
+
if ap_mac is not None: payload['ap_mac'] = ap_mac.lower()
|
|
283
|
+
return self._request(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload=payload)
|
|
284
|
+
|
|
285
|
+
"""
|
|
286
|
+
Unauthorize a client device.
|
|
287
|
+
|
|
288
|
+
Param string mac client MAC address
|
|
289
|
+
returns bool true upon success
|
|
290
|
+
throws Exception
|
|
291
|
+
"""
|
|
292
|
+
def unauthorize_guest(self, mac):
|
|
293
|
+
return self._request(
|
|
294
|
+
f"/api/s/{self._site}/cmd/stamgr",
|
|
295
|
+
method='POST',
|
|
296
|
+
payload={'cmd': 'unauthorize-guest', 'mac': mac}
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
def reconnect_sta(self, mac):
|
|
300
|
+
return self._request(
|
|
301
|
+
f"/api/s/{self._site}/cmd/stamgr",
|
|
302
|
+
method='POST',
|
|
303
|
+
payload={'cmd': 'kick-sta', 'mac': mac.lower()}
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
def block_sta(self, mac):
|
|
307
|
+
return self._request(
|
|
308
|
+
f"/api/s/{self._site}/cmd/stamgr",
|
|
309
|
+
method='POST',
|
|
310
|
+
payload={'cmd': 'block-sta', 'mac': mac.lower()}
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
def unblock_sta(self, mac):
|
|
314
|
+
return self._request(
|
|
315
|
+
f"/api/s/{self._site}/cmd/stamgr",
|
|
316
|
+
method='POST',
|
|
317
|
+
payload={'cmd': 'unblock-sta', 'mac': mac.lower()}
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
def forget_sta(self, mac):
|
|
321
|
+
return self._request(
|
|
322
|
+
f"/api/s/{self._site}/cmd/stamgr",
|
|
323
|
+
method='POST',
|
|
324
|
+
payload={'cmd': 'forget-sta', 'mac': mac}
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
def set_sta_note(self, user_id: str, note: str = '') -> bool:
|
|
328
|
+
"""Add or modify a client device note."""
|
|
329
|
+
payload = {'note': note}
|
|
330
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/upd/user/{user_id.strip()}", payload=payload)
|
|
331
|
+
|
|
332
|
+
def set_sta_name(self, user_id: str, name: str = '') -> bool:
|
|
333
|
+
"""Add or modify a client device name."""
|
|
334
|
+
payload = {'name': name}
|
|
335
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/upd/user/{user_id.strip()}", payload=payload)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
### Create Users
|
|
340
|
+
|
|
341
|
+
def create_user(self, mac: str, user_group_id: str ,name: str = None, note: str = None, is_guest: bool = None, is_wired: bool = None):
|
|
342
|
+
"""
|
|
343
|
+
Fully featured user creation matching the PHP client implementation
|
|
344
|
+
"""
|
|
345
|
+
new_user = {
|
|
346
|
+
'mac': mac.lower(),
|
|
347
|
+
'usergroup_id': user_group_id
|
|
348
|
+
}
|
|
349
|
+
if name:
|
|
350
|
+
new_user['name'] = name
|
|
351
|
+
if note:
|
|
352
|
+
new_user['note'] = note
|
|
353
|
+
if is_guest is not None:
|
|
354
|
+
new_user['is_guest'] = is_guest
|
|
355
|
+
if is_wired is not None:
|
|
356
|
+
new_user['is_wired'] = is_wired
|
|
357
|
+
|
|
358
|
+
payload = {
|
|
359
|
+
'objects': [{'data': new_user}]
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
self._curl_method = "POST"
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
return self.fetch_results(
|
|
366
|
+
f"/api/s/{self._site}/rest/user",
|
|
367
|
+
payload=payload
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
def delete_user(self, user_id: str):
|
|
371
|
+
"""
|
|
372
|
+
Remove a user by ID
|
|
373
|
+
"""
|
|
374
|
+
return self._request(f"/api/s/{self._site}/rest/user/{user_id}", method='DELETE')
|
|
375
|
+
|
|
376
|
+
def get_user(self, user_id: str):
|
|
377
|
+
"""
|
|
378
|
+
Retrieve a single user by ID.
|
|
379
|
+
"""
|
|
380
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/user/{user_id}")
|
|
381
|
+
|
|
382
|
+
def get_client_by_mac(self, mac: str):
|
|
383
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/user/{mac}")
|
|
384
|
+
|
|
385
|
+
def update_user(self, user_id: str, name: str = None, note: str = None, is_guest: bool = None, is_wired: bool = None):
|
|
386
|
+
"""
|
|
387
|
+
Update an existing user's details.
|
|
388
|
+
"""
|
|
389
|
+
|
|
390
|
+
payload = {}
|
|
391
|
+
if name is not None:
|
|
392
|
+
payload['name'] = name
|
|
393
|
+
if note is not None:
|
|
394
|
+
payload['note'] = note
|
|
395
|
+
if is_guest is not None:
|
|
396
|
+
payload['is_guest'] = is_guest
|
|
397
|
+
if is_wired is not None:
|
|
398
|
+
payload['is_wired'] = is_wired
|
|
399
|
+
|
|
400
|
+
return self.fetch_results(
|
|
401
|
+
f"/api/s/{self._site}/rest/user/{user_id}",
|
|
402
|
+
payload=payload
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
def forget_user(self, mac: str):
|
|
406
|
+
"""
|
|
407
|
+
Forget (remove) any record of a client's MAC from the site.
|
|
408
|
+
"""
|
|
409
|
+
return self._request(
|
|
410
|
+
f"/api/s/{self._site}/cmd/sitemgr",
|
|
411
|
+
method='POST',
|
|
412
|
+
payload={'cmd': 'forget-sta', 'mac': mac}
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
## Add them here
|
|
416
|
+
|
|
417
|
+
## ------------- Make sure these are included in the PHP files ------
|
|
418
|
+
def get_clients_summary(self):
|
|
419
|
+
return self._request(f"/api/s/{self._site}/stat/summary/client")
|
|
420
|
+
|
|
421
|
+
def get_user_groups(self):
|
|
422
|
+
return self._request(f"/api/s/{self._site}/list/usergroup")
|
|
423
|
+
|
|
424
|
+
def get_user_group(self, group_id):
|
|
425
|
+
return self._request(f"/api/s/{self._site}/list/usergroup/{group_id}")
|
|
426
|
+
|
|
427
|
+
def create_user_group(self, group_name: str, group_dn: int = -1, group_up: int = -1):
|
|
428
|
+
"""
|
|
429
|
+
Create a user group with download and upload QoS limits.
|
|
430
|
+
|
|
431
|
+
:param group_name: Name of the group
|
|
432
|
+
:param group_dn: Max download rate (kbps), -1 for unlimited
|
|
433
|
+
:param group_up: Max upload rate (kbps), -1 for unlimited
|
|
434
|
+
"""
|
|
435
|
+
payload = {
|
|
436
|
+
'name': group_name,
|
|
437
|
+
'qos_rate_max_down': group_dn,
|
|
438
|
+
'qos_rate_max_up': group_up,
|
|
439
|
+
}
|
|
440
|
+
return self.fetch_results(
|
|
441
|
+
f"/api/s/{self._site}/rest/usergroup",
|
|
442
|
+
payload=payload
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
def edit_user_group(self, group_id: str, site_id: str, group_name: str, group_dn: int = -1, group_up: int = -1):
|
|
446
|
+
"""
|
|
447
|
+
Edit an existing user group with new name or QoS limits.
|
|
448
|
+
"""
|
|
449
|
+
payload = {
|
|
450
|
+
'_id': group_id,
|
|
451
|
+
'name': group_name,
|
|
452
|
+
'qos_rate_max_down': group_dn,
|
|
453
|
+
'qos_rate_max_up': group_up,
|
|
454
|
+
'site_id': site_id,
|
|
455
|
+
}
|
|
456
|
+
return self._request(
|
|
457
|
+
f"/api/s/{self._site}/rest/usergroup",
|
|
458
|
+
method='PUT',
|
|
459
|
+
payload=payload
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
def delete_user_group(self, group_id):
|
|
463
|
+
return self._request(
|
|
464
|
+
f"/api/s/{self._site}/cmd/usergroup/{group_id}",
|
|
465
|
+
method='DELETE'
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def list_sites(self):
|
|
470
|
+
return self.fetch_results("/api/self/sites")
|
|
471
|
+
|
|
472
|
+
def list_apgroups(self):
|
|
473
|
+
"""
|
|
474
|
+
Fetch AP groups for the current site.
|
|
475
|
+
"""
|
|
476
|
+
return self._request(f"/v2/api/site/{self._site}/apgroups")
|
|
477
|
+
|
|
478
|
+
def create_apgroup(self, name: str, description: str = None) -> dict:
|
|
479
|
+
"""Create a new AP group with optional description."""
|
|
480
|
+
payload = {'name': name}
|
|
481
|
+
if description:
|
|
482
|
+
payload['description'] = description
|
|
483
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/apgroups", payload=payload)
|
|
484
|
+
|
|
485
|
+
def edit_apgroup(self, group_id: str, name: str = None, description: str = None) -> dict:
|
|
486
|
+
"""Modify an existing AP group."""
|
|
487
|
+
self._curl_method = 'PUT'
|
|
488
|
+
payload = {'_id': group_id}
|
|
489
|
+
if name:
|
|
490
|
+
payload['name'] = name
|
|
491
|
+
if description:
|
|
492
|
+
payload['description'] = description
|
|
493
|
+
result = self.fetch_results(f"/v2/api/site/{self._site}/apgroups/{group_id}", payload=payload)
|
|
494
|
+
self._curl_method = 'GET'
|
|
495
|
+
return result
|
|
496
|
+
|
|
497
|
+
def delete_apgroup(self, group_id: str) -> bool:
|
|
498
|
+
"""Delete an AP group."""
|
|
499
|
+
self._curl_method = 'DELETE'
|
|
500
|
+
result = self.fetch_results_boolean(f"/v2/api/site/{self._site}/apgroups/{group_id}")
|
|
501
|
+
self._curl_method = 'GET'
|
|
502
|
+
return result
|
|
503
|
+
|
|
504
|
+
def list_dashboard(self, five_minutes: bool = False):
|
|
505
|
+
"""Fetch dashboard metrics, 5-minute scale if requested."""
|
|
506
|
+
suffix = '?scale=5minutes' if five_minutes else ''
|
|
507
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/dashboard{suffix}")
|
|
508
|
+
|
|
509
|
+
def list_users(self):
|
|
510
|
+
"""Fetch known client devices."""
|
|
511
|
+
return self.fetch_results(f"/api/s/{self._site}/list/user", prefix_path=True)
|
|
512
|
+
|
|
513
|
+
def list_tags(self):
|
|
514
|
+
"""Fetch all device tags (REST)."""
|
|
515
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/tag")
|
|
516
|
+
|
|
517
|
+
def create_tag(self, tag_name: str, description: str = None) -> dict:
|
|
518
|
+
"""Create a new device tag."""
|
|
519
|
+
payload = {'name': tag_name}
|
|
520
|
+
if description:
|
|
521
|
+
payload['description'] = description
|
|
522
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/tag", payload=payload)
|
|
523
|
+
|
|
524
|
+
def delete_tag(self, tag_id: str) -> bool:
|
|
525
|
+
"""Delete a device tag."""
|
|
526
|
+
self._curl_method = 'DELETE'
|
|
527
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/tag/{tag_id}")
|
|
528
|
+
self._curl_method = 'GET'
|
|
529
|
+
return result
|
|
530
|
+
|
|
531
|
+
def get_tag(self, tag_id: str):
|
|
532
|
+
"""Retrieve a specific device tag."""
|
|
533
|
+
self._curl_method = 'GET'
|
|
534
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/tag/{tag_id}")
|
|
535
|
+
|
|
536
|
+
def list_known_rogueaps(self):
|
|
537
|
+
"""Fetch known rogue access points."""
|
|
538
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/rogueknown")
|
|
539
|
+
|
|
540
|
+
def get_site(self, site_id) -> str:
|
|
541
|
+
return self._request(f"/api/s/{site_id}/self")
|
|
542
|
+
|
|
543
|
+
def create_site(self, description: str):
|
|
544
|
+
"""
|
|
545
|
+
Create a new site with a given description.
|
|
546
|
+
"""
|
|
547
|
+
payload = {
|
|
548
|
+
'desc': description,
|
|
549
|
+
'cmd': 'add-site',
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
self._curl_method = "POST"
|
|
553
|
+
|
|
554
|
+
if self._unifi_os:
|
|
555
|
+
# UniFi OS uses the /api/self/sites endpoint
|
|
556
|
+
return self.fetch_results(
|
|
557
|
+
"/api/self/sites",
|
|
558
|
+
payload=payload
|
|
559
|
+
)
|
|
560
|
+
else:
|
|
561
|
+
# Classic controller
|
|
562
|
+
return self.fetch_results(
|
|
563
|
+
f"/api/s/{self._site}/cmd/sitemgr",
|
|
564
|
+
payload=payload
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
self._curl_method = "GET"
|
|
568
|
+
|
|
569
|
+
def delete_site(self, site_id):
|
|
570
|
+
return self._request(
|
|
571
|
+
f"/api/s/{site_id}",
|
|
572
|
+
method='DELETE',
|
|
573
|
+
payload={'site': site_id, 'cmd': 'delete-site'}
|
|
574
|
+
)
|
|
575
|
+
|
|
576
|
+
def set_site(self, site: str) -> str:
|
|
577
|
+
self._check_site(site)
|
|
578
|
+
self._site = site.strip()
|
|
579
|
+
|
|
580
|
+
return self._site
|
|
581
|
+
|
|
582
|
+
def set_site_name(self, site_name: str) -> bool:
|
|
583
|
+
"""Change the current site's long name."""
|
|
584
|
+
payload = {'cmd': 'update-site', 'desc': site_name}
|
|
585
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
586
|
+
|
|
587
|
+
def set_site_locale(self, locale_id: str, payload: dict) -> bool:
|
|
588
|
+
"""Update the site's locale settings."""
|
|
589
|
+
self._curl_method = 'PUT'
|
|
590
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/setting/locale/{locale_id.strip()}", payload=payload)
|
|
591
|
+
self._curl_method = 'GET'
|
|
592
|
+
return result
|
|
593
|
+
|
|
594
|
+
def set_site_snmp(self, snmp_id: str, payload: dict) -> bool:
|
|
595
|
+
"""Update site SNMP settings"""
|
|
596
|
+
self._curl_method = 'PUT'
|
|
597
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/setting/snmp/{snmp_id.strip()}", payload=payload)
|
|
598
|
+
self._curl_method = 'GET'
|
|
599
|
+
return result
|
|
600
|
+
|
|
601
|
+
def set_site_mgmt(self, mgmt_id: str, payload: dict) -> bool:
|
|
602
|
+
"""Update site management settings"""
|
|
603
|
+
self._curl_method = 'PUT'
|
|
604
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/setting/mgmt/{mgmt_id.strip()}", payload=payload)
|
|
605
|
+
self._curl_method = 'GET'
|
|
606
|
+
return result
|
|
607
|
+
|
|
608
|
+
def set_site_guest_access(self, guest_access_id: str, payload: dict) -> bool:
|
|
609
|
+
"""Update site guest access settings"""
|
|
610
|
+
self._curl_method = 'PUT'
|
|
611
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/setting/guest_access/{guest_access_id.strip()}", payload=payload)
|
|
612
|
+
self._curl_method = 'GET'
|
|
613
|
+
return result
|
|
614
|
+
|
|
615
|
+
def set_site_ntp(self, ntp_id: str, payload: dict) -> bool:
|
|
616
|
+
"""Update site NTP settings"""
|
|
617
|
+
self._curl_method = 'PUT'
|
|
618
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/setting/ntp/{ntp_id.strip()}", payload=payload)
|
|
619
|
+
self._curl_method = 'GET'
|
|
620
|
+
return result
|
|
621
|
+
|
|
622
|
+
def set_site_connectivity(self, connectivity_id: str, payload: dict) -> bool:
|
|
623
|
+
"""Update site connectivity settings"""
|
|
624
|
+
self._curl_method = 'PUT'
|
|
625
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/setting/connectivity/{connectivity_id.strip()}", payload=payload)
|
|
626
|
+
self._curl_method = 'GET'
|
|
627
|
+
return result
|
|
628
|
+
|
|
629
|
+
def set_site_country(self, country_id: str, payload) -> bool:
|
|
630
|
+
self._curl_method = "PUT"
|
|
631
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/rest/setting/country/{country_id.strip()}", payload=payload)
|
|
632
|
+
|
|
633
|
+
def get_admins(self):
|
|
634
|
+
"""Fetch administrators for current site"""
|
|
635
|
+
payload = {'cmd': 'get-admins'}
|
|
636
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/sitemgr", payload=payload, prefix_path=True)
|
|
637
|
+
|
|
638
|
+
def list_all_admins(self):
|
|
639
|
+
"""Fetch all administrators"""
|
|
640
|
+
payload = {'cmd': 'get-all-admins'}
|
|
641
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
642
|
+
|
|
643
|
+
def invite_admin(self, name: str, email: str, enable_sso: bool = True, readonly: bool = False,
|
|
644
|
+
device_adopt: bool = False, device_restart: bool = False) -> bool:
|
|
645
|
+
"""Invite a new or existing admin"""
|
|
646
|
+
email = email.strip()
|
|
647
|
+
payload = {'cmd': 'create-admin', 'name': name, 'email': email, 'role': 'admin', 'permissions': []}
|
|
648
|
+
# SSO control
|
|
649
|
+
payload['sso_enabled'] = enable_sso
|
|
650
|
+
# Validate email
|
|
651
|
+
if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
|
|
652
|
+
raise EmailInvalidException()
|
|
653
|
+
# Role assignment
|
|
654
|
+
if readonly:
|
|
655
|
+
payload['role'] = 'readonly'
|
|
656
|
+
# Permissions
|
|
657
|
+
if device_adopt:
|
|
658
|
+
payload['permissions'].append('API_DEVICE_ADOPT')
|
|
659
|
+
if device_restart:
|
|
660
|
+
payload['permissions'].append('API_DEVICE_RESTART')
|
|
661
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
662
|
+
|
|
663
|
+
def assign_existing_admin(self, admin_id: str, readonly: bool = False,
|
|
664
|
+
device_adopt: bool = False, device_restart: bool = False) -> bool:
|
|
665
|
+
"""Assign an existing admin to this site"""
|
|
666
|
+
payload = {'cmd': 'grant-admin', 'admin': admin_id.strip(), 'role': 'admin', 'permissions': []}
|
|
667
|
+
if readonly:
|
|
668
|
+
payload['role'] = 'readonly'
|
|
669
|
+
if device_adopt:
|
|
670
|
+
payload['permissions'].append('API_DEVICE_ADOPT')
|
|
671
|
+
if device_restart:
|
|
672
|
+
payload['permissions'].append('API_DEVICE_RESTART')
|
|
673
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
674
|
+
|
|
675
|
+
def update_admin(self, admin_id: str, name: str, email: str, password: str = '',
|
|
676
|
+
readonly: bool = False, device_adopt: bool = False, device_restart: bool = False) -> bool:
|
|
677
|
+
"""Update admin user properties"""
|
|
678
|
+
email = email.strip()
|
|
679
|
+
if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
|
|
680
|
+
raise EmailInvalidException()
|
|
681
|
+
payload = {'cmd': 'update-admin', 'admin': admin_id.strip(), 'name': name.strip(), 'email': email, 'password': password, 'role': 'admin', 'permissions': []}
|
|
682
|
+
if readonly:
|
|
683
|
+
payload['role'] = 'readonly'
|
|
684
|
+
if device_adopt:
|
|
685
|
+
payload['permissions'].append('API_DEVICE_ADOPT')
|
|
686
|
+
if device_restart:
|
|
687
|
+
payload['permissions'].append('API_DEVICE_RESTART')
|
|
688
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
689
|
+
|
|
690
|
+
def revoke_admin(self, admin_id: str) -> bool:
|
|
691
|
+
"""Revoke an admin's access to this site"""
|
|
692
|
+
payload = {'cmd': 'revoke-admin', 'admin': admin_id.strip()}
|
|
693
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
694
|
+
|
|
695
|
+
def delete_admin(self, admin_id: str) -> bool:
|
|
696
|
+
"""Delete an admin user"""
|
|
697
|
+
payload = {'cmd': 'delete-admin', 'admin': admin_id.strip()}
|
|
698
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
699
|
+
|
|
700
|
+
def list_wlan_groups(self):
|
|
701
|
+
"""Fetch WLAN groups"""
|
|
702
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/wlangroup")
|
|
703
|
+
|
|
704
|
+
def stat_sysinfo(self):
|
|
705
|
+
"""Fetch system info stat"""
|
|
706
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/sysinfo")
|
|
707
|
+
|
|
708
|
+
def stat_status(self) -> bool:
|
|
709
|
+
"""Fetch controller online status"""
|
|
710
|
+
return self.fetch_results_boolean(
|
|
711
|
+
'/status',
|
|
712
|
+
payload=None,
|
|
713
|
+
login_required=self._unifi_os
|
|
714
|
+
)
|
|
715
|
+
|
|
716
|
+
def stat_full_status(self):
|
|
717
|
+
"""Fetch full controller status"""
|
|
718
|
+
# Ensure login if required and fetch boolean to populate last_results_raw
|
|
719
|
+
self.fetch_results_boolean(
|
|
720
|
+
'/status',
|
|
721
|
+
payload=None,
|
|
722
|
+
login_required=self._unifi_os
|
|
723
|
+
)
|
|
724
|
+
# Decode and return the last raw JSON results
|
|
725
|
+
raw = self.get_last_results_raw(return_json=False)
|
|
726
|
+
try:
|
|
727
|
+
return json.loads(raw)
|
|
728
|
+
except (TypeError, json.JSONDecodeError):
|
|
729
|
+
return raw
|
|
730
|
+
|
|
731
|
+
def list_device_name_mappings(self):
|
|
732
|
+
"""Fetch device name MIB mappings"""
|
|
733
|
+
# Populate last_results_raw via boolean fetch
|
|
734
|
+
self.fetch_results_boolean(
|
|
735
|
+
'/dl/firmware/bundles.json',
|
|
736
|
+
payload=None,
|
|
737
|
+
login_required=self._unifi_os
|
|
738
|
+
)
|
|
739
|
+
# Decode and return JSON
|
|
740
|
+
raw = self.get_last_results_raw(return_json=False)
|
|
741
|
+
try:
|
|
742
|
+
return json.loads(raw)
|
|
743
|
+
except (TypeError, json.JSONDecodeError):
|
|
744
|
+
return raw(f"/api/s/{self._site}/list/device/name_mapping")
|
|
745
|
+
|
|
746
|
+
def list_self(self):
|
|
747
|
+
"""Fetch details of the current user"""
|
|
748
|
+
return self.fetch_results('/api/self')
|
|
749
|
+
|
|
750
|
+
def get_devices(self):
|
|
751
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/device", login_required=True, prefix_path=True)
|
|
752
|
+
|
|
753
|
+
def get_device(self, device_id):
|
|
754
|
+
return self._request(f"/api/s/{self._site}/stat/device/{device_id}")
|
|
755
|
+
|
|
756
|
+
def get_wlan(self, wlan_id: str):
|
|
757
|
+
"""
|
|
758
|
+
Retrieve WLAN configuration by ID
|
|
759
|
+
"""
|
|
760
|
+
return self._request(f"/api/s/{self._site}/rest/wlanconf/{wlan_id}")
|
|
761
|
+
|
|
762
|
+
def list_wlanconf(self):
|
|
763
|
+
"""
|
|
764
|
+
List all WLAN configurations on the site.
|
|
765
|
+
"""
|
|
766
|
+
return self._request(f"/api/s/{self._site}/rest/wlanconf")
|
|
767
|
+
|
|
768
|
+
def create_wlan(
|
|
769
|
+
self,
|
|
770
|
+
name: str,
|
|
771
|
+
x_passphrase: str,
|
|
772
|
+
usergroup_id: str,
|
|
773
|
+
wlangroup_id: str,
|
|
774
|
+
enabled: bool = True,
|
|
775
|
+
hide_ssid: bool = False,
|
|
776
|
+
is_guest: bool = False,
|
|
777
|
+
security: str = 'open',
|
|
778
|
+
wpa_mode: str = 'wpa2',
|
|
779
|
+
wpa_enc: str = 'ccmp',
|
|
780
|
+
vlan_enabled: bool = None,
|
|
781
|
+
vlan_id: str = None,
|
|
782
|
+
uapsd_enabled: bool = False,
|
|
783
|
+
schedule_enabled: bool = False,
|
|
784
|
+
schedule: list = None,
|
|
785
|
+
ap_group_ids: list = None,
|
|
786
|
+
payload: dict = None
|
|
787
|
+
) -> bool:
|
|
788
|
+
"""
|
|
789
|
+
Create a new WLAN with full parameter support matching the PHP client.
|
|
790
|
+
"""
|
|
791
|
+
data = payload.copy() if payload is not None else {}
|
|
792
|
+
# Merge required/default fields
|
|
793
|
+
data.update({
|
|
794
|
+
'name': name.strip(),
|
|
795
|
+
'usergroup_id': usergroup_id.strip(),
|
|
796
|
+
'wlangroup_id': wlangroup_id.strip(),
|
|
797
|
+
'enabled': enabled,
|
|
798
|
+
'hide_ssid': hide_ssid,
|
|
799
|
+
'is_guest': is_guest,
|
|
800
|
+
'security': security.strip(),
|
|
801
|
+
'wpa_mode': wpa_mode.strip(),
|
|
802
|
+
'wpa_enc': wpa_enc.strip(),
|
|
803
|
+
'uapsd_enabled': uapsd_enabled,
|
|
804
|
+
'schedule_enabled': schedule_enabled,
|
|
805
|
+
'schedule': schedule or [],
|
|
806
|
+
})
|
|
807
|
+
if vlan_id is not None:
|
|
808
|
+
data['networkconf_id'] = vlan_id
|
|
809
|
+
if x_passphrase and security != 'open':
|
|
810
|
+
data['x_passphrase'] = x_passphrase.strip()
|
|
811
|
+
if ap_group_ids is not None:
|
|
812
|
+
data['ap_group_ids'] = ap_group_ids
|
|
813
|
+
|
|
814
|
+
# Perform the request and return True on HTTP 200
|
|
815
|
+
self._request(
|
|
816
|
+
f"/api/s/{self._site}/add/wlanconf",
|
|
817
|
+
method='POST',
|
|
818
|
+
payload=data
|
|
819
|
+
)
|
|
820
|
+
return self._last_response_code == 200
|
|
821
|
+
|
|
822
|
+
def set_wlansettings_base(self, wlan_id: str, payload: dict) -> bool:
|
|
823
|
+
"""Base REST call to update WLAN settings."""
|
|
824
|
+
self._curl_method = 'PUT'
|
|
825
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/wlanconf/{wlan_id.strip()}", payload=payload)
|
|
826
|
+
self._curl_method = 'GET'
|
|
827
|
+
return result
|
|
828
|
+
|
|
829
|
+
def set_wlansettings(self, wlan_id: str, x_passphrase: str, name: str = '') -> bool:
|
|
830
|
+
"""Update basic WLAN settings (passphrase and SSID)."""
|
|
831
|
+
payload = {'x_passphrase': x_passphrase.strip()}
|
|
832
|
+
if name:
|
|
833
|
+
payload['name'] = name.strip()
|
|
834
|
+
return self.set_wlansettings_base(wlan_id, payload)
|
|
835
|
+
|
|
836
|
+
def disable_wlan(self, wlan_id: str, disable: bool) -> bool:
|
|
837
|
+
"""Disable or enable a WLAN network."""
|
|
838
|
+
action = not disable
|
|
839
|
+
payload = {'enabled': action}
|
|
840
|
+
return self.set_wlansettings_base(wlan_id, payload)
|
|
841
|
+
|
|
842
|
+
def set_wlan_mac_filter(self, wlan_id: str, policy: str, enable: bool, macs: list) -> bool:
|
|
843
|
+
"""Set MAC filter policy and list for a WLAN."""
|
|
844
|
+
if policy not in ['allow', 'deny']:
|
|
845
|
+
return False
|
|
846
|
+
macs = [m.lower() for m in macs]
|
|
847
|
+
payload = {'mac_filter_enabled': enable, 'mac_filter_policy': policy, 'mac_filter_list': macs}
|
|
848
|
+
return self.set_wlansettings_base(wlan_id, payload)
|
|
849
|
+
|
|
850
|
+
def set_wlan_passphrase(self, wlan_id: str, x_passphrase: str, name: str = None):
|
|
851
|
+
"""
|
|
852
|
+
Update PSK/passphrase and optionally name (mirros set_wlansettings in PHP)
|
|
853
|
+
"""
|
|
854
|
+
|
|
855
|
+
data = {}
|
|
856
|
+
if x_passphrase:
|
|
857
|
+
data['x_passphrase'] = x_passphrase.strip()
|
|
858
|
+
if name is not None:
|
|
859
|
+
data['name'] = name.strip()
|
|
860
|
+
return self._request(
|
|
861
|
+
f"/api/s/{self._site}/rest/wlanconf/{wlan_id}",
|
|
862
|
+
method='PUT',
|
|
863
|
+
payload=data
|
|
864
|
+
)
|
|
865
|
+
|
|
866
|
+
def delete_wlan(self, wlan_id: str):
|
|
867
|
+
"""
|
|
868
|
+
Delete a WLAN configuration by ID
|
|
869
|
+
"""
|
|
870
|
+
return self._request(
|
|
871
|
+
f"/api/s/{self._site}/rest/wlanconf/{wlan_id.strip()}"
|
|
872
|
+
)
|
|
873
|
+
|
|
874
|
+
def cmd_stat(self, command: str) -> bool:
|
|
875
|
+
"""Execute specific stats commands, e.g., 'reset-dpi'."""
|
|
876
|
+
if command != 'reset-dpi':
|
|
877
|
+
return False
|
|
878
|
+
payload = {'cmd': command}
|
|
879
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/stat", payload=payload)
|
|
880
|
+
|
|
881
|
+
def set_element_adoption(self, enable: bool) -> bool:
|
|
882
|
+
"""Toggle Element Adoption setting."""
|
|
883
|
+
payload = {'enabled': enable}
|
|
884
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/set/setting/element_adopt", payload=payload)
|
|
885
|
+
|
|
886
|
+
def spectrum_scan(self, mac: str) -> bool:
|
|
887
|
+
"""Trigger RF spectrum scan on an AP."""
|
|
888
|
+
payload = {'cmd': 'spectrum-scan', 'mac': mac.lower()}
|
|
889
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr", payload=payload)
|
|
890
|
+
|
|
891
|
+
def spectrum_scan_state(self, mac: str):
|
|
892
|
+
"""Fetch RF scan state/results for an AP."""
|
|
893
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/spectrum-scan/{mac.lower().strip()}")
|
|
894
|
+
|
|
895
|
+
def set_device_settings_base(self, device_id: str, payload: dict) -> bool:
|
|
896
|
+
"""Base REST call to update device settings."""
|
|
897
|
+
self._curl_method = 'PUT'
|
|
898
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/device/{device_id.strip()}", payload=payload)
|
|
899
|
+
self._curl_method = 'GET'
|
|
900
|
+
return result
|
|
901
|
+
|
|
902
|
+
def power_cycle_switch_port(self, mac: str, port_idx: int) -> bool:
|
|
903
|
+
"""Power-cycle a PoE switch port."""
|
|
904
|
+
payload = {'mac': mac.lower(), 'port_idx': port_idx, 'cmd': 'power-cycle'}
|
|
905
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr", payload=payload)
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def list_guests(self, within: int = 8760):
|
|
910
|
+
"""
|
|
911
|
+
Retrieve all active guest sessions on the site within the last 'within' seconds
|
|
912
|
+
"""
|
|
913
|
+
payload = {'within': within}
|
|
914
|
+
return self.fetch_results(
|
|
915
|
+
f"/api/s/{self._site}/stat/guest",
|
|
916
|
+
payload=payload
|
|
917
|
+
)
|
|
918
|
+
|
|
919
|
+
## same as list_guest but for mac
|
|
920
|
+
def list_clients(self, mac: str = None):
|
|
921
|
+
"""Fetch online client devices, or single device if MAC provided."""
|
|
922
|
+
path_mac = mac.lower().strip() if isinstance(mac, str) else ''
|
|
923
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/sta/{path_mac}")
|
|
924
|
+
|
|
925
|
+
def list_active_clients(self, include_traffic_usage: bool = True, include_unifi_devices: bool = True):
|
|
926
|
+
"""Fetch active client devices, with optional traffic and UniFi device inclusion."""
|
|
927
|
+
query = urlencode({
|
|
928
|
+
'include_traffic_usage': include_traffic_usage,
|
|
929
|
+
'include_unifi_devices': include_unifi_devices,
|
|
930
|
+
})
|
|
931
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/clients/active?{query}")
|
|
932
|
+
|
|
933
|
+
def list_clients_history(self, only_non_blocked: bool = True, include_unifi_devices: bool = True, within_hours: int = 0):
|
|
934
|
+
"""Fetch offline client device history."""
|
|
935
|
+
query = urlencode({
|
|
936
|
+
'only_non_blocked': only_non_blocked,
|
|
937
|
+
'include_unifi_devices': include_unifi_devices,
|
|
938
|
+
'within_hours': within_hours,
|
|
939
|
+
})
|
|
940
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/clients/history?{query}")
|
|
941
|
+
|
|
942
|
+
def expire_guest(self, mac: str):
|
|
943
|
+
"""
|
|
944
|
+
Expire (unauthorize) a guest session immedietely
|
|
945
|
+
"""
|
|
946
|
+
return self._request(
|
|
947
|
+
f"/api/s/{self._site}/cmd/stamgr",
|
|
948
|
+
method='POST',
|
|
949
|
+
payload={'cmd': 'unauthorize-guest', 'mac': mac}
|
|
950
|
+
)
|
|
951
|
+
|
|
952
|
+
def list_vouchers(self):
|
|
953
|
+
"""
|
|
954
|
+
List all hotspot vouchers on the site.
|
|
955
|
+
"""
|
|
956
|
+
return self._request(f"/api/s/{self._site}/stat/voucher")
|
|
957
|
+
|
|
958
|
+
def create_voucher(
|
|
959
|
+
self,
|
|
960
|
+
minutes: int,
|
|
961
|
+
count: int = 1,
|
|
962
|
+
quota: int = 0,
|
|
963
|
+
note: str = '',
|
|
964
|
+
up: int = None,
|
|
965
|
+
down: int = None,
|
|
966
|
+
megabytes: int = None
|
|
967
|
+
):
|
|
968
|
+
|
|
969
|
+
"""
|
|
970
|
+
Create new hotspot vouchers with full options.
|
|
971
|
+
:param minutes: time-to-live in minutes
|
|
972
|
+
:param count: number of vouchers to generate
|
|
973
|
+
:param quota: total quota in bytes (0 for unlimited)
|
|
974
|
+
:param note: optional note for the vouchers
|
|
975
|
+
:param up: optional upload rate limit (kbps)
|
|
976
|
+
:param down: optional download rate limit (kbps)
|
|
977
|
+
:param megabytes: optional byte quota per voucher
|
|
978
|
+
"""
|
|
979
|
+
payload = {
|
|
980
|
+
'cmd': 'create-voucher',
|
|
981
|
+
'expire': minutes,
|
|
982
|
+
'n': count,
|
|
983
|
+
'quota': quota
|
|
984
|
+
}
|
|
985
|
+
if note:
|
|
986
|
+
payload['note'] = note.strip()
|
|
987
|
+
if up is not None:
|
|
988
|
+
payload['up'] = up
|
|
989
|
+
if down is not None:
|
|
990
|
+
payload['down'] = down
|
|
991
|
+
if megabytes is not None:
|
|
992
|
+
payload['bytes'] = megabytes
|
|
993
|
+
|
|
994
|
+
return self._request(
|
|
995
|
+
f"/api/s/{self._site}/cmd/hotspot",
|
|
996
|
+
method='POST',
|
|
997
|
+
payload=payload
|
|
998
|
+
)
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def revoke_voucher(self, voucher_id: str):
|
|
1003
|
+
"""
|
|
1004
|
+
Delete a specific voucher by its ID
|
|
1005
|
+
"""
|
|
1006
|
+
payload = {'_id': voucher_id, 'cmd': 'delete-voucher'}
|
|
1007
|
+
|
|
1008
|
+
return self._request(
|
|
1009
|
+
f"/api/s/{self._site}/cmd/hotspot",
|
|
1010
|
+
method='POST',
|
|
1011
|
+
payload=payload
|
|
1012
|
+
)
|
|
1013
|
+
|
|
1014
|
+
def list_sessions(self):
|
|
1015
|
+
"""
|
|
1016
|
+
List all client sessions (stat/session) for the site
|
|
1017
|
+
"""
|
|
1018
|
+
return self._request(f"/api/s/{self._site}/stat/session")
|
|
1019
|
+
|
|
1020
|
+
def stat_hourly_site(self, start: int = None, end: int = None, attribs: list = None):
|
|
1021
|
+
"""
|
|
1022
|
+
Retrieve hourly site statistics report.
|
|
1023
|
+
:param start: start timestamp in ms (defaults to 7 days ago)
|
|
1024
|
+
:param end: end timestamp in ms (defaults to now)
|
|
1025
|
+
:param attribs: list of attributes to return (defaults to ['time'] + default_site_stats_attribs)
|
|
1026
|
+
"""
|
|
1027
|
+
now_ms = int(time.time() * 1000)
|
|
1028
|
+
end = end if end is not None else now_ms
|
|
1029
|
+
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1030
|
+
default_attrs = getattr(self, 'default_site_stats_attribs', [])
|
|
1031
|
+
attribs = attribs if attribs is not None else ['time'] + default_attrs
|
|
1032
|
+
|
|
1033
|
+
payload = {
|
|
1034
|
+
'attrs': attribs,
|
|
1035
|
+
'start': start,
|
|
1036
|
+
'end': end
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
return self._request(
|
|
1040
|
+
f"/api/s/{self._site}/stat/report/hourly.site",
|
|
1041
|
+
method='GET',
|
|
1042
|
+
payload=payload
|
|
1043
|
+
)
|
|
1044
|
+
|
|
1045
|
+
def stat_5minutes_site(self, start: int = None, end: int = None, attribs: list = None):
|
|
1046
|
+
"""Fetch 5-minute site stats (defaults to past 12 hours)."""
|
|
1047
|
+
end = end or int(time.time() * 1000)
|
|
1048
|
+
start = start or end - 12 * 3600 * 1000
|
|
1049
|
+
attrs = attribs or self.default_site_stats_attribs
|
|
1050
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1051
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.site", payload=payload)
|
|
1052
|
+
|
|
1053
|
+
def stat_5minutes_aps(self, start: int = None, end: int = None, mac: str = None, attribs: list = None):
|
|
1054
|
+
"""Fetch 5-minute AP stats (defaults to past 12 hours)."""
|
|
1055
|
+
end = end or int(time.time() * 1000)
|
|
1056
|
+
start = start or end - 12 * 3600 * 1000
|
|
1057
|
+
attrs = attribs or self.default_ap_stats_attribs
|
|
1058
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1059
|
+
if mac:
|
|
1060
|
+
payload['mac'] = mac.lower()
|
|
1061
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.ap", payload=payload)
|
|
1062
|
+
|
|
1063
|
+
def stat_hourly_aps(self, start: int = None, end: int = None, mac: str = None, attribs: list = None):
|
|
1064
|
+
"""Fetch hourly AP stats (defaults to past 7 days)."""
|
|
1065
|
+
end = end or int(time.time() * 1000)
|
|
1066
|
+
start = start or end - 7 * 24 * 3600 * 1000
|
|
1067
|
+
attrs = attribs or self.default_ap_stats_attribs
|
|
1068
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1069
|
+
if mac:
|
|
1070
|
+
payload['mac'] = mac.lower()
|
|
1071
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/hourly.ap", payload=payload)
|
|
1072
|
+
|
|
1073
|
+
def stat_daily_aps(self, start: int = None, end: int = None, mac: str = None, attribs: list = None):
|
|
1074
|
+
"""Fetch daily AP stats (defaults to past 7 days)."""
|
|
1075
|
+
now = int(time.time())
|
|
1076
|
+
end = end or (now - (now % 3600)) * 1000
|
|
1077
|
+
start = start or end - 7 * 24 * 3600 * 1000
|
|
1078
|
+
attrs = attribs or self.default_ap_stats_attribs
|
|
1079
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1080
|
+
if mac:
|
|
1081
|
+
payload['mac'] = mac.lower()
|
|
1082
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/daily.ap", payload=payload)
|
|
1083
|
+
|
|
1084
|
+
def stat_monthly_aps(self, start: int = None, end: int = None, mac: str = None, attribs: list = None):
|
|
1085
|
+
"""Fetch monthly AP stats (defaults to past 52 weeks)."""
|
|
1086
|
+
now = int(time.time())
|
|
1087
|
+
end = end or (now - (now % 3600)) * 1000
|
|
1088
|
+
start = start or end - 52 * 7 * 24 * 3600 * 1000
|
|
1089
|
+
attrs = attribs or self.default_ap_stats_attribs
|
|
1090
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1091
|
+
if mac:
|
|
1092
|
+
payload['mac'] = mac.lower()
|
|
1093
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/monthly.ap", payload=payload)
|
|
1094
|
+
|
|
1095
|
+
def stat_5minutes_user(self, mac: str = None, start: int = None, end: int = None, attribs: list = None):
|
|
1096
|
+
"""Fetch 5-minute user stats (defaults to past 12 hours)."""
|
|
1097
|
+
end = end or int(time.time() * 1000)
|
|
1098
|
+
start = start or end - 12 * 3600 * 1000
|
|
1099
|
+
attrs = attribs or ['time', 'rx_bytes', 'tx_bytes']
|
|
1100
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1101
|
+
if mac:
|
|
1102
|
+
payload['mac'] = mac.lower()
|
|
1103
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.user", payload=payload)
|
|
1104
|
+
|
|
1105
|
+
def stat_hourly_user(self, mac: str = None, start: int = None, end: int = None, attribs: list = None):
|
|
1106
|
+
"""Fetch hourly user stats (defaults to past 7 days)."""
|
|
1107
|
+
end = end or int(time.time() * 1000)
|
|
1108
|
+
start = start or end - 7 * 24 * 3600 * 1000
|
|
1109
|
+
attrs = attribs or ['time', 'rx_bytes', 'tx_bytes']
|
|
1110
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1111
|
+
if mac:
|
|
1112
|
+
payload['mac'] = mac.lower()
|
|
1113
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/hourly.user", payload=payload)
|
|
1114
|
+
|
|
1115
|
+
def stat_daily_user(self, mac: str = None, start: int = None, end: int = None, attribs: list = None):
|
|
1116
|
+
"""Fetch daily user stats (defaults to past 7 days)."""
|
|
1117
|
+
end = end or int(time.time() * 1000)
|
|
1118
|
+
start = start or end - 7 * 24 * 3600 * 1000
|
|
1119
|
+
attrs = attribs or ['time', 'rx_bytes', 'tx_bytes']
|
|
1120
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1121
|
+
if mac:
|
|
1122
|
+
payload['mac'] = mac.lower()
|
|
1123
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/daily.user", payload=payload)
|
|
1124
|
+
|
|
1125
|
+
def stat_monthly_user(self, mac: str = None, start: int = None, end: int = None, attribs: list = None):
|
|
1126
|
+
"""Fetch monthly user stats (defaults to past 52 weeks)."""
|
|
1127
|
+
now = int(time.time())
|
|
1128
|
+
end = end or (now - (now % 3600)) * 1000
|
|
1129
|
+
start = start or end - 52 * 7 * 24 * 3600 * 1000
|
|
1130
|
+
attrs = attribs or ['time', 'rx_bytes', 'tx_bytes']
|
|
1131
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1132
|
+
if mac:
|
|
1133
|
+
payload['mac'] = mac.lower()
|
|
1134
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/monthly.user", payload=payload)
|
|
1135
|
+
|
|
1136
|
+
def stat_5minutes_gateway(self, start: int = None, end: int = None, attribs: list = None):
|
|
1137
|
+
"""Fetch 5-minute gateway stats (defaults to past 12 hours)."""
|
|
1138
|
+
end = end or int(time.time() * 1000)
|
|
1139
|
+
start = start or end - 12 * 3600 * 1000
|
|
1140
|
+
attrs = attribs or ['time', 'mem', 'cpu', 'loadavg_5']
|
|
1141
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1142
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.gw", payload=payload)
|
|
1143
|
+
|
|
1144
|
+
def stat_hourly_gateway(self, start: int = None, end: int = None, attribs: list = None):
|
|
1145
|
+
"""Fetch hourly gateway stats (defaults to past 7 days)."""
|
|
1146
|
+
end = end or int(time.time() * 1000)
|
|
1147
|
+
start = start or end - 7 * 24 * 3600 * 1000
|
|
1148
|
+
attrs = attribs or ['time', 'mem', 'cpu', 'loadavg_5']
|
|
1149
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1150
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/hourly.gw", payload=payload)
|
|
1151
|
+
|
|
1152
|
+
def stat_daily_gateway(self, start: int = None, end: int = None, attribs: list = None):
|
|
1153
|
+
"""Fetch daily gateway stats (defaults to past 52 weeks)."""
|
|
1154
|
+
now = int(time.time())
|
|
1155
|
+
end = end or (now - (now % 3600)) * 1000
|
|
1156
|
+
start = start or end - 52 * 7 * 24 * 3600 * 1000
|
|
1157
|
+
attrs = attribs or ['time', 'mem', 'cpu', 'loadavg_5']
|
|
1158
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1159
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/daily.gw", payload=payload)
|
|
1160
|
+
|
|
1161
|
+
def stat_monthly_gateway(self, start: int = None, end: int = None, attribs: list = None):
|
|
1162
|
+
"""Fetch monthly gateway stats (defaults to past 52 weeks)."""
|
|
1163
|
+
now = int(time.time())
|
|
1164
|
+
end = end or (now - (now % 3600)) * 1000
|
|
1165
|
+
start = start or end - 52 * 7 * 24 * 3600 * 1000
|
|
1166
|
+
attrs = attribs or ['time', 'mem', 'cpu', 'loadavg_5']
|
|
1167
|
+
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1168
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/monthly.gw", payload=payload)
|
|
1169
|
+
|
|
1170
|
+
def list_network(self, network_id: str = ''):
|
|
1171
|
+
return self._request(f"/api/s/{self._site}/rest/networkconf{network_id.strip()}")
|
|
1172
|
+
|
|
1173
|
+
def list_networkconf(self, network_id: str = ''):
|
|
1174
|
+
return self._request(f"/api/s/{self._site}/rest/networkconf{network_id.strip()}")
|
|
1175
|
+
|
|
1176
|
+
def list_backups(self):
|
|
1177
|
+
payload = {'cmd': 'list-backups'}
|
|
1178
|
+
|
|
1179
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/backup", payload=payload, prefix_path=True)
|
|
1180
|
+
|
|
1181
|
+
def get_network(self, network_id: str):
|
|
1182
|
+
"""
|
|
1183
|
+
Get a specific network configuration by ID
|
|
1184
|
+
"""
|
|
1185
|
+
return self._request(f"/api/s/{self._site}/rest/networkconf/{network_id}")
|
|
1186
|
+
|
|
1187
|
+
def create_network(self, payload: dict):
|
|
1188
|
+
"""
|
|
1189
|
+
Create a new network configuration
|
|
1190
|
+
"""
|
|
1191
|
+
return self._request(
|
|
1192
|
+
f"/api/s/{self._site}/rest/networkconf",
|
|
1193
|
+
method='POST',
|
|
1194
|
+
payload=payload
|
|
1195
|
+
)
|
|
1196
|
+
|
|
1197
|
+
def set_networksettings_base(self, network_id: str, update_fields: dict):
|
|
1198
|
+
"""
|
|
1199
|
+
Update an existing network configuration
|
|
1200
|
+
"""
|
|
1201
|
+
return self._request(
|
|
1202
|
+
f"/api/s/{self._site}/rest/networkconf/{network_id}",
|
|
1203
|
+
method='PUT',
|
|
1204
|
+
payload=update_fields
|
|
1205
|
+
)
|
|
1206
|
+
|
|
1207
|
+
def delete_network(self, network_id: str):
|
|
1208
|
+
"""
|
|
1209
|
+
Delete a network configuration by ID
|
|
1210
|
+
"""
|
|
1211
|
+
return self._request(
|
|
1212
|
+
f"/api/s/{self._site}/rest/networkconf{network_id.strip()}",
|
|
1213
|
+
method='DELETE'
|
|
1214
|
+
)
|
|
1215
|
+
|
|
1216
|
+
def list_portconf(self):
|
|
1217
|
+
"""
|
|
1218
|
+
List all port configurations on the site.
|
|
1219
|
+
"""
|
|
1220
|
+
return self._request(f"/api/s/{self._site}/list/portconf")
|
|
1221
|
+
|
|
1222
|
+
def get_portconf(self, portconf_id: str):
|
|
1223
|
+
"""
|
|
1224
|
+
Retrieve port configuration by ID
|
|
1225
|
+
"""
|
|
1226
|
+
return self._request(f"/api/s/{self._site}/rest/portconf/{portconf_id}")
|
|
1227
|
+
|
|
1228
|
+
def create_portconf(self, config: dict):
|
|
1229
|
+
"""
|
|
1230
|
+
Create a new port configuration.
|
|
1231
|
+
"""
|
|
1232
|
+
return self._request(
|
|
1233
|
+
f"/api/s/{self._site}/rest/portconf",
|
|
1234
|
+
method='POST',
|
|
1235
|
+
payload=config
|
|
1236
|
+
)
|
|
1237
|
+
|
|
1238
|
+
def set_portconf(self, portconf_id: str, config: dict):
|
|
1239
|
+
"""
|
|
1240
|
+
Update an existing port configuration.
|
|
1241
|
+
"""
|
|
1242
|
+
return self._request(
|
|
1243
|
+
f"/api/s/{self._site}/rest/portconf/{portconf_id}",
|
|
1244
|
+
method='PUT',
|
|
1245
|
+
payload=config
|
|
1246
|
+
)
|
|
1247
|
+
|
|
1248
|
+
def delete_portconf(self, portconf_id: str):
|
|
1249
|
+
"""
|
|
1250
|
+
Delete a port configuration by ID.
|
|
1251
|
+
"""
|
|
1252
|
+
return self._request(
|
|
1253
|
+
f"/api/s/{self._site}/rest/portconf/{portconf_id}",
|
|
1254
|
+
method='DELETE'
|
|
1255
|
+
)
|
|
1256
|
+
|
|
1257
|
+
def stat_ips_events(self, start: int = None, end: int = None, limit: int = None):
|
|
1258
|
+
"""Fetch IPS/IDS events (defaults to past 24 hours)."""
|
|
1259
|
+
end = end or int(time.time() * 1000)
|
|
1260
|
+
start = start or end - (24 * 3600 * 1000)
|
|
1261
|
+
limit = limit or 10000
|
|
1262
|
+
payload = {'start': start, 'end': end, '_limit': limit}
|
|
1263
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/ips/event", payload=payload)
|
|
1264
|
+
|
|
1265
|
+
def stat_sta_sessions(self, mac: str, start: int = None, end: int = None):
|
|
1266
|
+
"""
|
|
1267
|
+
Retrieve client sessions within a time window.
|
|
1268
|
+
"""
|
|
1269
|
+
end = end if end is not None else int(time.time() * 1000)
|
|
1270
|
+
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1271
|
+
payload = {'mac': mac, 'start': start, 'end': end}
|
|
1272
|
+
return self._request(f"/api/s/{self._site}/stat/session", method='POST', payload=payload)
|
|
1273
|
+
|
|
1274
|
+
def stat_sta_sessions_latest(self, mac: str, limit: int = None):
|
|
1275
|
+
"""Fetch latest 'n' login sessions for a client (defaults to 5)."""
|
|
1276
|
+
limit = limit or 5
|
|
1277
|
+
payload = {'mac': mac.lower(), '_limit': limit, '_sort': '-assoc_time'}
|
|
1278
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/session", payload=payload)
|
|
1279
|
+
|
|
1280
|
+
def stat_sta(self, mac: str, start: int = None, end: int = None):
|
|
1281
|
+
"""
|
|
1282
|
+
Retrieve stats for a specific client (STA).
|
|
1283
|
+
"""
|
|
1284
|
+
end = end if end is not None else int(time.time() * 1000)
|
|
1285
|
+
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1286
|
+
payload = {'mac': mac, 'start': start, 'end': end}
|
|
1287
|
+
return self._request(f"/api/s/{self._site}/stat/user", method='POST', payload=payload)
|
|
1288
|
+
|
|
1289
|
+
def stat_all_user(self, start: int = None, end: int = None):
|
|
1290
|
+
"""
|
|
1291
|
+
Retrieve usage stats for all users within a time window.
|
|
1292
|
+
"""
|
|
1293
|
+
end = end if end is not None else int(time.time() * 1000)
|
|
1294
|
+
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1295
|
+
payload = {'start': start, 'end': end}
|
|
1296
|
+
return self._request(f"/api/s/{self._site}/stat/alluser", method='POST', payload=payload)
|
|
1297
|
+
|
|
1298
|
+
def stat_allusers(self, historyhours: int = 8760):
|
|
1299
|
+
"""Fetch clients seen within the past N hours (all-time totals)."""
|
|
1300
|
+
payload = {'type': 'all', 'conn': 'all', 'within': historyhours}
|
|
1301
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/alluser", payload=payload)
|
|
1302
|
+
|
|
1303
|
+
def stat_daily_site(self, start: int = None, end: int = None, attribs: list = None):
|
|
1304
|
+
"""
|
|
1305
|
+
Retrieve daily site statistics with selected attributes.
|
|
1306
|
+
"""
|
|
1307
|
+
end = end if end is not None else int(time.time() * 1000)
|
|
1308
|
+
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1309
|
+
attribs = ['time'] + attribs if attribs else ['time'] + self.default_site_stats_attribs
|
|
1310
|
+
payload = {'attrs': attribs, 'start': start, 'end': end}
|
|
1311
|
+
return self._request(f"/api/s/{self._site}/stat/report/daily.site", method='POST', payload=payload)
|
|
1312
|
+
|
|
1313
|
+
def stat_monthly_site(self, start: int = None, end: int = None, attribs: list = None):
|
|
1314
|
+
"""
|
|
1315
|
+
Retrieve monthly site statistics with selected attributes.
|
|
1316
|
+
"""
|
|
1317
|
+
end = end if end is not None else int(time.time() * 1000)
|
|
1318
|
+
start = start if start is not None else end - (30 * 24 * 3600 * 1000)
|
|
1319
|
+
attribs = ['time'] + attribs if attribs else ['time'] + self.default_site_stats_attribs
|
|
1320
|
+
payload = {'attrs': attribs, 'start': start, 'end': end}
|
|
1321
|
+
return self._request(f"/api/s/{self._site}/stat/report/monthly.site", method='POST', payload=payload)
|
|
1322
|
+
|
|
1323
|
+
def stat_current_user(self):
|
|
1324
|
+
"""
|
|
1325
|
+
Get stats for currently connected users.
|
|
1326
|
+
"""
|
|
1327
|
+
return self._request(f"/api/s/{self._site}/stat/sta")
|
|
1328
|
+
|
|
1329
|
+
def stat_all_users(self):
|
|
1330
|
+
"""
|
|
1331
|
+
Get usage stats for all known users.
|
|
1332
|
+
"""
|
|
1333
|
+
return self._request(f"/api/s/{self._site}/stat/alluser")
|
|
1334
|
+
|
|
1335
|
+
def stat_voucher(self, create_time: int = None):
|
|
1336
|
+
"""
|
|
1337
|
+
Fetch statistics about vouchers, optionally filtering by creation time
|
|
1338
|
+
"""
|
|
1339
|
+
payload = {'create_time': create_time} if create_time is not None else {}
|
|
1340
|
+
return self._request(f"/api/s/{self._site}/stat/voucher", payload=payload)
|
|
1341
|
+
|
|
1342
|
+
def stat_payment(self, within: int=None):
|
|
1343
|
+
"""
|
|
1344
|
+
Fetch statistics about payments, optionally filtering by time window
|
|
1345
|
+
"""
|
|
1346
|
+
path_suffix = f"?within={within}" if within is not None else ""
|
|
1347
|
+
return self._request(f"api/s/{self._site}/stat/payment{path_suffix}")
|
|
1348
|
+
|
|
1349
|
+
def create_hotspotop(self, name: str, x_password: str, note: str = '') -> bool:
|
|
1350
|
+
"""Create hotspot operator user"""
|
|
1351
|
+
payload = {'cmd': 'create-hotspotop', 'name': name, 'x_password': x_password}
|
|
1352
|
+
if note:
|
|
1353
|
+
payload['note'] = note.strip()
|
|
1354
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/hotspot", payload=payload)
|
|
1355
|
+
|
|
1356
|
+
def list_hotspotop(self):
|
|
1357
|
+
"""List hotspot operators"""
|
|
1358
|
+
return self.fetch_results(f"/api/s/{self._site}/list/hotspotop")
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
|
|
1362
|
+
def stat_auths(self, start: int = None, end: int = None):
|
|
1363
|
+
"""
|
|
1364
|
+
Fetch authorizatoin statistics within a time window
|
|
1365
|
+
"""
|
|
1366
|
+
end = end if end is not None else int(time.time())
|
|
1367
|
+
start = start if start is not None else end - (7 * 24 * 3600)
|
|
1368
|
+
payload = {'start': start, 'end': end}
|
|
1369
|
+
return self._request(f"/api/s/{self._site}/stat/authorization", payload=payload)
|
|
1370
|
+
|
|
1371
|
+
def stat_sessions(self, start: int = None, end: int = None, mac: str = None, type: str = 'all'):
|
|
1372
|
+
"""
|
|
1373
|
+
Retrieve session statistics with optional filtering.
|
|
1374
|
+
"""
|
|
1375
|
+
if type not in ['all', 'guest', 'user']:
|
|
1376
|
+
return False
|
|
1377
|
+
|
|
1378
|
+
end = end if end is not None else int(time.time())
|
|
1379
|
+
start = start if start is not None else end - (7 * 24 * 3600)
|
|
1380
|
+
payload = {'type': type, 'start': start, 'end': end}
|
|
1381
|
+
|
|
1382
|
+
if mac:
|
|
1383
|
+
payload['mac'] = mac.lower()
|
|
1384
|
+
|
|
1385
|
+
return self._request(f"/api/s/{self._site}/stat/session", payload=payload)
|
|
1386
|
+
|
|
1387
|
+
def stat_client(self, mac: str):
|
|
1388
|
+
"""Fetch details for a single client device."""
|
|
1389
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/user/{mac.lower().strip()}")
|
|
1390
|
+
|
|
1391
|
+
def list_fingerprint_devices(self, fingerprint_source: int = 0):
|
|
1392
|
+
"""Fetch client fingerprint devices (default source 0)."""
|
|
1393
|
+
return self.fetch_results(f"/v2/api/fingerprint_devices/{fingerprint_source}")
|
|
1394
|
+
|
|
1395
|
+
def set_usergroup(self, client_id: str, group_id: str) -> bool:
|
|
1396
|
+
"""Assign a client device to a user group."""
|
|
1397
|
+
payload = {'usergroup_id': group_id}
|
|
1398
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/upd/user/{client_id.strip()}", payload=payload)
|
|
1399
|
+
|
|
1400
|
+
def list_usergroups(self):
|
|
1401
|
+
"""Fetch all user groups."""
|
|
1402
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/usergroup")
|
|
1403
|
+
|
|
1404
|
+
def create_usergroup(self, group_name: str, qos_rate_max_down: int = -1, qos_rate_max_up: int = -1):
|
|
1405
|
+
"""Create a new user group via REST."""
|
|
1406
|
+
payload = {'name': group_name, 'qos_rate_max_down': qos_rate_max_down, 'qos_rate_max_up': qos_rate_max_up}
|
|
1407
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/usergroup", payload=payload)
|
|
1408
|
+
|
|
1409
|
+
def edit_usergroup(self, group_id: str, group_name: str, qos_rate_max_down: int = None, qos_rate_max_up: int = None):
|
|
1410
|
+
"""Modify an existing user group via REST."""
|
|
1411
|
+
self._curl_method = 'PUT'
|
|
1412
|
+
payload = {'_id': group_id, 'name': group_name}
|
|
1413
|
+
if qos_rate_max_down is not None:
|
|
1414
|
+
payload['qos_rate_max_down'] = qos_rate_max_down
|
|
1415
|
+
if qos_rate_max_up is not None:
|
|
1416
|
+
payload['qos_rate_max_up'] = qos_rate_max_up
|
|
1417
|
+
result = self.fetch_results(f"/api/s/{self._site}/rest/usergroup/{group_id.strip()}", payload=payload)
|
|
1418
|
+
self._curl_method = 'GET'
|
|
1419
|
+
return result
|
|
1420
|
+
|
|
1421
|
+
def delete_usergroup(self, group_id: str) -> bool:
|
|
1422
|
+
"""Delete a user group via REST."""
|
|
1423
|
+
self._curl_method = 'DELETE'
|
|
1424
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/usergroup/{group_id.strip()}")
|
|
1425
|
+
self._curl_method = 'GET'
|
|
1426
|
+
return result
|
|
1427
|
+
|
|
1428
|
+
def edit_client_fixedip(self, client_id: str, use_fixedip: bool, network_id: str = None, fixed_ip: str = None):
|
|
1429
|
+
"""Update a client device's fixed IP via REST."""
|
|
1430
|
+
self._curl_method = 'PUT'
|
|
1431
|
+
payload = {'_id': client_id, 'use_fixedip': use_fixedip}
|
|
1432
|
+
if use_fixedip:
|
|
1433
|
+
if network_id:
|
|
1434
|
+
payload['network_id'] = network_id
|
|
1435
|
+
if fixed_ip:
|
|
1436
|
+
payload['fixed_ip'] = fixed_ip
|
|
1437
|
+
result = self.fetch_results(f"/api/s/{self._site}/rest/user/{client_id.strip()}", payload=payload)
|
|
1438
|
+
self._curl_method = 'GET'
|
|
1439
|
+
return result
|
|
1440
|
+
|
|
1441
|
+
def edit_client_name(self, client_id: str, name: str):
|
|
1442
|
+
"""Update a client device's name via REST."""
|
|
1443
|
+
|
|
1444
|
+
if not name:
|
|
1445
|
+
return False
|
|
1446
|
+
|
|
1447
|
+
self._curl_method = 'PUT'
|
|
1448
|
+
payload = {'_id': client_id, 'name': name}
|
|
1449
|
+
result = self.fetch_results(f"/api/s/{self._site}/rest/user/{client_id.strip()}", payload=payload)
|
|
1450
|
+
self._curl_method = 'GET'
|
|
1451
|
+
return result
|
|
1452
|
+
|
|
1453
|
+
def list_alarms(self, payload: dict = None):
|
|
1454
|
+
"""
|
|
1455
|
+
Retrieve list of alarms with optional filtering payload
|
|
1456
|
+
"""
|
|
1457
|
+
payload = payload or {}
|
|
1458
|
+
return self._request(f"/api/s/{self._site}/list/alarm", payload=payload)
|
|
1459
|
+
|
|
1460
|
+
def list_events(self, historyhours: int = 720, start: int = 0, limit: int = 3000):
|
|
1461
|
+
payload = {
|
|
1462
|
+
'_sort': '-time',
|
|
1463
|
+
'within': historyhours,
|
|
1464
|
+
'type': null,
|
|
1465
|
+
'_start': start,
|
|
1466
|
+
'_limit': limit
|
|
1467
|
+
}
|
|
1468
|
+
return self._request(f"/api/s/{self._site}/stat/event", payload=payload)
|
|
1469
|
+
|
|
1470
|
+
def list_tags(self):
|
|
1471
|
+
return self._request(f"/api/s/{self._site}/rest/tag")
|
|
1472
|
+
|
|
1473
|
+
def list_dpi_stats(self):
|
|
1474
|
+
"""
|
|
1475
|
+
List DPI stats.
|
|
1476
|
+
"""
|
|
1477
|
+
return self._request(f"/api/s/{self._site}/stat/dpi")
|
|
1478
|
+
|
|
1479
|
+
def list_dpi_stats_filtered(self, type: str = 'by_cat', cat_filter: list = None):
|
|
1480
|
+
"""
|
|
1481
|
+
Retrieve DPI stats filtered by category or application
|
|
1482
|
+
"""
|
|
1483
|
+
if type not in ['by_cat', 'by_app']:
|
|
1484
|
+
return False
|
|
1485
|
+
|
|
1486
|
+
payload = {'type': type}
|
|
1487
|
+
|
|
1488
|
+
if isinstance(cat_filter, list) and type == 'by_app':
|
|
1489
|
+
payload['cats'] = cat_filter
|
|
1490
|
+
|
|
1491
|
+
return self._request(f"/api/s/{self._site}/stat/sitedpi", payload=payload)
|
|
1492
|
+
|
|
1493
|
+
def list_dpi_app_categories(self):
|
|
1494
|
+
"""Fetch DPI application categories."""
|
|
1495
|
+
return self.fetch_results(f"/api/s/{self._site}/list/dpi/application/categories")
|
|
1496
|
+
|
|
1497
|
+
def list_dpi_app(self):
|
|
1498
|
+
"""Fetch DPI applications."""
|
|
1499
|
+
return self.fetch_results(f"/api/s/{self._site}/list/dpi/application")
|
|
1500
|
+
|
|
1501
|
+
def create_dpi_app(self, name: str, category: str, description: str = None) -> dict:
|
|
1502
|
+
"""Create a new DPI application."""
|
|
1503
|
+
payload = {'name': name, 'category': category}
|
|
1504
|
+
if description:
|
|
1505
|
+
payload['description'] = description
|
|
1506
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/dpi/application", payload=payload)
|
|
1507
|
+
|
|
1508
|
+
def list_country_codes(self):
|
|
1509
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/ccode")
|
|
1510
|
+
|
|
1511
|
+
def list_radius_accounts(self):
|
|
1512
|
+
return self._request(f"/api/s/{self._site}/rest/account")
|
|
1513
|
+
|
|
1514
|
+
def list_radius_profiles(self):
|
|
1515
|
+
"""Fetch RADIUS profiles"""
|
|
1516
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/radiusprofile")
|
|
1517
|
+
|
|
1518
|
+
def create_radius_account(self, name: str, x_password: str, tunnel_type: int = None, tunnel_medium_type: int = None, vlan: str = None) -> dict:
|
|
1519
|
+
"""Create a Radius user account with optional tunneling parameters and VLAN"""
|
|
1520
|
+
# Validate tunnel parameters
|
|
1521
|
+
valid_tunnel_types = {None, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
|
|
1522
|
+
valid_medium_types = {None, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
|
|
1523
|
+
if tunnel_type not in valid_tunnel_types or tunnel_medium_type not in valid_medium_types or ((tunnel_type is None) ^ (tunnel_medium_type is None)):
|
|
1524
|
+
return False
|
|
1525
|
+
|
|
1526
|
+
payload = {'name': name, 'x_password': x_password}
|
|
1527
|
+
if tunnel_type is not None:
|
|
1528
|
+
payload['tunnel_type'] = tunnel_type
|
|
1529
|
+
if tunnel_medium_type is not None:
|
|
1530
|
+
payload['tunnel_medium_type'] = tunnel_medium_type
|
|
1531
|
+
if vlan is not None:
|
|
1532
|
+
payload['vlan'] = vlan
|
|
1533
|
+
|
|
1534
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/account", payload=payload)
|
|
1535
|
+
|
|
1536
|
+
def set_radius_account_base(self, account_id: str, payload) -> bool:
|
|
1537
|
+
self._curl_method = "PUT"
|
|
1538
|
+
|
|
1539
|
+
return self.fetch_results_boolean(f'/api/s/{self._site}/rest/account/{account_id.strip()}', payload=payload)
|
|
1540
|
+
|
|
1541
|
+
def get_system_log(
|
|
1542
|
+
self,
|
|
1543
|
+
class_: str = 'device-alert',
|
|
1544
|
+
start: int = None,
|
|
1545
|
+
end: int = None,
|
|
1546
|
+
page_number: int = 0,
|
|
1547
|
+
page_size: int = 100,
|
|
1548
|
+
custom_payload: dict = None
|
|
1549
|
+
) -> list:
|
|
1550
|
+
"""Fetch system logs filtered by class and time window with pagination"""
|
|
1551
|
+
# Determine time window
|
|
1552
|
+
now_ms = int(time.time() * 1000)
|
|
1553
|
+
end_ts = end if end is not None else now_ms
|
|
1554
|
+
start_ts = start if start is not None else end_ts - (7 * 24 * 3600 * 1000)
|
|
1555
|
+
|
|
1556
|
+
# Base payload
|
|
1557
|
+
payload = {
|
|
1558
|
+
'pageNumber': page_number,
|
|
1559
|
+
'pageSize': page_size,
|
|
1560
|
+
'timestampFrom': start_ts,
|
|
1561
|
+
'timestampTo': end_ts,
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
# Class-specific filters
|
|
1565
|
+
if class_ == 'next-ai-alert':
|
|
1566
|
+
payload['nextAiCategory'] = ['CLIENT', 'DEVICE', 'INTERNET', 'VPN']
|
|
1567
|
+
elif class_ == 'admin-activity':
|
|
1568
|
+
payload['activity_keys'] = ['ACCESSED_NETWORK_WEB', 'ACCESSED_NETWORK_IOS', 'ACCESSED_NETWORK_ANDROID']
|
|
1569
|
+
payload['change_keys'] = ['CLIENT', 'DEVICE', 'HOTSPOT', 'INTERNET', 'NETWORK', 'PROFILE', 'ROUTING', 'SECURITY', 'SYSTEM', 'VPN', 'WIFI']
|
|
1570
|
+
elif class_ == 'update-alert':
|
|
1571
|
+
payload['systemLogDeviceTypes'] = ['GATEWAYS', 'SWITCHES', 'ACCESS_POINT', 'SMART_POWER', 'BUILDING_TO_BUILDING_BRIDGES', 'UNIFI_LTE']
|
|
1572
|
+
elif class_ == 'client-alert':
|
|
1573
|
+
payload['clientType'] = ['GUEST', 'TELEPORT', 'VPN', 'WIRELESS', 'RADIUS', 'WIRED']
|
|
1574
|
+
payload['guestAuthorizationMethod'] = ['FACEBOOK_SOCIAL_GATEWAY', 'FREE_TRIAL', 'GOOGLE_SOCIAL_GATEWAY', 'NONE', 'PASSWORD', 'PAYMENT', 'RADIUS', 'VOUCHER']
|
|
1575
|
+
elif class_ == 'threat-alert':
|
|
1576
|
+
payload['threatTypes'] = ['HONEYPOT', 'THREAT']
|
|
1577
|
+
elif class_ == 'triggers':
|
|
1578
|
+
payload['triggerTypes'] = ['TRAFFIC_RULE', 'TRAFFIC_ROUTE', 'FIREWALL_RULE']
|
|
1579
|
+
|
|
1580
|
+
# Merge any custom payload overrides
|
|
1581
|
+
if custom_payload:
|
|
1582
|
+
payload.update(custom_payload)
|
|
1583
|
+
|
|
1584
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/system-log{class_}", payload=custom_payload)
|
|
1585
|
+
|
|
1586
|
+
def delete_radius_account(self, account_id: str) -> bool:
|
|
1587
|
+
"""Delete a Radius user account"""
|
|
1588
|
+
self._curl_method = 'DELETE'
|
|
1589
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/account/{account_id.strip()}")
|
|
1590
|
+
self._curl_method = 'GET'
|
|
1591
|
+
return result
|
|
1592
|
+
|
|
1593
|
+
def list_readius_profiles(self):
|
|
1594
|
+
return self._request(f"/api/s/{self._site}/rest/radiusprofile")
|
|
1595
|
+
|
|
1596
|
+
def list_hotspot_operators(self):
|
|
1597
|
+
return self._request(f"api/s/{self._site}/rest/hotspotop")
|
|
1598
|
+
|
|
1599
|
+
def count_alarms(self, archived: bool = None):
|
|
1600
|
+
"""
|
|
1601
|
+
Count alarms; if archived=False counts only non-archived
|
|
1602
|
+
"""
|
|
1603
|
+
suffix = '?archived=false' if archived is False else ''
|
|
1604
|
+
return self._request(f"/api/s/{self._site}/cnt/alarm{suffix}")
|
|
1605
|
+
|
|
1606
|
+
def archive_alarm(self, alarm_id: str = '') -> bool:
|
|
1607
|
+
"""
|
|
1608
|
+
Archive alarms; specific alarm or all
|
|
1609
|
+
"""
|
|
1610
|
+
if alarm_id:
|
|
1611
|
+
payload = {'_id': alarm_id, 'cmd': 'archive-alarm'}
|
|
1612
|
+
else:
|
|
1613
|
+
payload = {'cmd': 'archive-all-alarms'}
|
|
1614
|
+
self._request(f"/api/s/{self._site}/cmd/evtmgr", method="POST", payload=payload)
|
|
1615
|
+
return self._last_response_code == 200
|
|
1616
|
+
|
|
1617
|
+
def stat_speedtest_results(self, start: int = None, end: int = None):
|
|
1618
|
+
"""
|
|
1619
|
+
Retrieve speed test results with optional start and end times.
|
|
1620
|
+
"""
|
|
1621
|
+
end = end if end is not None else int(time.time() * 1000)
|
|
1622
|
+
start = start if start is not None else end - (24 * 3600 * 1000)
|
|
1623
|
+
payload = {
|
|
1624
|
+
'attrs': ['xput_download', 'xput_upload', 'latency', 'time'],
|
|
1625
|
+
'start': start,
|
|
1626
|
+
'end': end
|
|
1627
|
+
}
|
|
1628
|
+
return self._request(f"/api/s/{self._site}/stat/report/archive.speedtest", payload=payload)
|
|
1629
|
+
|
|
1630
|
+
def list_health(self):
|
|
1631
|
+
return self._request(f"/api/s/{self._site}/stat/heatlh")
|
|
1632
|
+
|
|
1633
|
+
def stat_user_devices(self):
|
|
1634
|
+
"""
|
|
1635
|
+
Retrieve statistics on user devices.
|
|
1636
|
+
"""
|
|
1637
|
+
return self._request(f"/api/s/{self._site}/stat/user/devices")
|
|
1638
|
+
|
|
1639
|
+
def stat_sites(self):
|
|
1640
|
+
"""
|
|
1641
|
+
Retrieve statistics for all available sites.
|
|
1642
|
+
"""
|
|
1643
|
+
return self._request("/api/stat/sites")
|
|
1644
|
+
|
|
1645
|
+
def list_devices(self, macs: list[str] = []):
|
|
1646
|
+
"""
|
|
1647
|
+
Fetch UniFi devices, optionally filtered by MAC addresses.
|
|
1648
|
+
"""
|
|
1649
|
+
payload = {'macs': [mac.lower() for mac in macs]}
|
|
1650
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/device", payload=payload)
|
|
1651
|
+
|
|
1652
|
+
def list_devices_basic(self):
|
|
1653
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/device-basic")
|
|
1654
|
+
|
|
1655
|
+
def check_controller_update(self):
|
|
1656
|
+
"""
|
|
1657
|
+
Fetch latest known controller version info
|
|
1658
|
+
"""
|
|
1659
|
+
return self._request(f"/api/s/{self._site}/stat/fwupdate/latest-version")
|
|
1660
|
+
|
|
1661
|
+
def get_update_os_console(self):
|
|
1662
|
+
"""
|
|
1663
|
+
Get recent firmware update for UniFi OS console
|
|
1664
|
+
"""
|
|
1665
|
+
if not self._unifi_os:
|
|
1666
|
+
raise NotAUnifiOsConsoleException()
|
|
1667
|
+
return self._request('/api/firmware/update')
|
|
1668
|
+
|
|
1669
|
+
def update_os_console(self) -> bool:
|
|
1670
|
+
"""
|
|
1671
|
+
Trigger UniFi OS update
|
|
1672
|
+
"""
|
|
1673
|
+
if not self._unifi_os:
|
|
1674
|
+
raise NotAUnifiOsConsoleException()
|
|
1675
|
+
payload = {'persistFullData': True}
|
|
1676
|
+
self._request(f"/api/s/{self._site}/cmd/firmware/update", method='POST', payload=payload)
|
|
1677
|
+
return self._last_response_code == 200
|
|
1678
|
+
|
|
1679
|
+
|
|
1680
|
+
## ---------- Deprecated Methods ---------
|
|
1681
|
+
def list_aps(self):
|
|
1682
|
+
raise MethodDeprecatedException('Function list_aps() has been deprecated, use list_devices() instead.')
|
|
1683
|
+
|
|
1684
|
+
def set_locate_ap(self):
|
|
1685
|
+
raise MethodDeprecatedException('Function set_locate_ap() has been deprecated, use locate_ap() instead.')
|
|
1686
|
+
|
|
1687
|
+
def unset_locate_ap(self) -> bool:
|
|
1688
|
+
raise MethodDeprecatedException('Function unset_locate_ap() has been deprecated, use locate_ap() instead.')
|
|
1689
|
+
|
|
1690
|
+
def site_ledson(self) -> bool:
|
|
1691
|
+
raise MethodDeprecatedException('Function site_ledson() has been deprecated, use site_leds() instead.')
|
|
1692
|
+
|
|
1693
|
+
def site_ledsoff(self) -> bool:
|
|
1694
|
+
raise MethodDeprecatedException('Function site_ledsoff() has been deprecated, use site_leds() instead.')
|
|
1695
|
+
|
|
1696
|
+
def restart_ap(self) -> bool:
|
|
1697
|
+
raise MethodDeprecatedException('Function restart_ap() has been deprecated, use restart_device() instead.')
|
|
1698
|
+
|
|
1699
|
+
def get_class_version(self) -> str:
|
|
1700
|
+
return self.CLASS_VERSION
|
|
1701
|
+
|
|
1702
|
+
def get_site(self) -> str:
|
|
1703
|
+
return self._site
|
|
1704
|
+
|
|
1705
|
+
def set_debug(self) -> bool:
|
|
1706
|
+
return getattr(self, '_debug', False)
|
|
1707
|
+
|
|
1708
|
+
def get_last_results_raw(self, return_json: bool = False):
|
|
1709
|
+
"""Raw API response"""
|
|
1710
|
+
if self._last_results_raw is not None:
|
|
1711
|
+
if return_json:
|
|
1712
|
+
return json.dumps(self._last_results_raw, indent=4)
|
|
1713
|
+
return self._last_results_raw
|
|
1714
|
+
return False
|
|
1715
|
+
|
|
1716
|
+
def get_last_error_message(self) -> str:
|
|
1717
|
+
"""Error message of last operation"""
|
|
1718
|
+
return self._last_error_message
|
|
1719
|
+
|
|
1720
|
+
def set_cookies(self, cookies_value: str) -> None:
|
|
1721
|
+
"""
|
|
1722
|
+
Set the value for cookies and update timestamp
|
|
1723
|
+
"""
|
|
1724
|
+
self._cookies = cookies_value
|
|
1725
|
+
self._cookies_created_at = int(time.time())
|
|
1726
|
+
|
|
1727
|
+
def get_unificookie_name(self) -> str:
|
|
1728
|
+
"""Get current UniFi cookie name"""
|
|
1729
|
+
return self._unificookie_nam
|
|
1730
|
+
|
|
1731
|
+
def get_curl_method(self) -> str:
|
|
1732
|
+
"""Get current HTTP request method"""
|
|
1733
|
+
return self._curl_method
|
|
1734
|
+
|
|
1735
|
+
def set_curl_method(self, curl_method: str) -> str:
|
|
1736
|
+
if curl_method not in self.CURL_METHODS_ALLOWED:
|
|
1737
|
+
raise InvalidCurlMethodException()
|
|
1738
|
+
self._curl_method = curl_method
|
|
1739
|
+
return self._curl_method
|
|
1740
|
+
|
|
1741
|
+
def get_curl_ssl_verify_peer(self) -> bool:
|
|
1742
|
+
"""Get SSL verify peer setting"""
|
|
1743
|
+
return self._curl_ssl_verify_peer
|
|
1744
|
+
|
|
1745
|
+
def set_curl_ssl_verify_peer(self, curl_ssl_verify_peer: bool) -> bool:
|
|
1746
|
+
"""Enable or disable SSL peer verification"""
|
|
1747
|
+
self._curl_ssl_verify_peer = curl_ssl_verify_peer
|
|
1748
|
+
return True
|
|
1749
|
+
|
|
1750
|
+
def get_curl_ssl_verify_host(self) -> int:
|
|
1751
|
+
"""Get SSL verify host setting"""
|
|
1752
|
+
return self._curl_ssl_verify_host
|
|
1753
|
+
|
|
1754
|
+
def set_curl_ssl_verify_host(self, curl_ssl_verify_host: int) -> bool:
|
|
1755
|
+
"""Set SSL verify host level"""
|
|
1756
|
+
if curl_ssl_verify_host not in [0, 1, 2]:
|
|
1757
|
+
return False
|
|
1758
|
+
|
|
1759
|
+
self._curl_ssl_verify_host = curl_ssl_verify_host
|
|
1760
|
+
return True
|
|
1761
|
+
|
|
1762
|
+
def get_is_unifi_os(self) -> bool:
|
|
1763
|
+
"""Check if connected controller is UniFi OS-based"""
|
|
1764
|
+
return self._unifi_os
|
|
1765
|
+
|
|
1766
|
+
def set_is_unifi_os(self, is_unifi_os: bool) -> bool:
|
|
1767
|
+
"""Flag controller as UniFi OS-based or not"""
|
|
1768
|
+
self._unifi_os = is_unifi_os
|
|
1769
|
+
return True
|
|
1770
|
+
|
|
1771
|
+
def set_connection_timeout(self, timeout: int) -> bool:
|
|
1772
|
+
"""Set connection timeout in seconds"""
|
|
1773
|
+
self._connection_timeout = timeout
|
|
1774
|
+
return True
|
|
1775
|
+
|
|
1776
|
+
def get_connection_timeout(self) -> int:
|
|
1777
|
+
"""Get current connection timeout"""
|
|
1778
|
+
return self._connect_timeout
|
|
1779
|
+
|
|
1780
|
+
def set_curl_request_timeout(self, timeout: int) -> bool:
|
|
1781
|
+
"""Set request timeout in seconds"""
|
|
1782
|
+
self._request_timeout = timeout
|
|
1783
|
+
return True
|
|
1784
|
+
|
|
1785
|
+
def get_curl_request_timeout(self) -> int:
|
|
1786
|
+
"""Get current request timeout"""
|
|
1787
|
+
return self._request_timeout
|
|
1788
|
+
|
|
1789
|
+
def set_curl_http_version(self, http_version: int) -> bool:
|
|
1790
|
+
"""Specify HTTP version for requests"""
|
|
1791
|
+
self._curl_http_version = http_version
|
|
1792
|
+
return True
|
|
1793
|
+
|
|
1794
|
+
def get_curl_http_version(self) -> int:
|
|
1795
|
+
"""Get HTTP version currently set"""
|
|
1796
|
+
return self._curl_http_version
|
|
1797
|
+
|
|
1798
|
+
# ----- Protected Helper Methods -----
|
|
1799
|
+
|
|
1800
|
+
def fetch_results_boolean(self, path: str, payload=None, login_required: bool = True, prefix_path: bool = True) -> bool:
|
|
1801
|
+
return self.fetch_results(path, payload, boolean=True, login_required=login_required, prefix_path=prefix_path)
|
|
1802
|
+
|
|
1803
|
+
def _get_json_last_error(self) -> bool:
|
|
1804
|
+
try:
|
|
1805
|
+
json.loads(self._last_results_raw)
|
|
1806
|
+
return True
|
|
1807
|
+
except json.JSONDecodeError as e:
|
|
1808
|
+
# Try to match the error message like PHP's cases
|
|
1809
|
+
message = e.msg.lower()
|
|
1810
|
+
|
|
1811
|
+
if "depth" in message:
|
|
1812
|
+
error = "The maximum stack depth has been exceeded"
|
|
1813
|
+
elif "expecting" in message or "syntax" in message:
|
|
1814
|
+
error = "Syntax error, malformed JSON"
|
|
1815
|
+
elif "control character" in message:
|
|
1816
|
+
error = "Control character error, possibly incorrectly encoded"
|
|
1817
|
+
elif "utf-8" in message:
|
|
1818
|
+
error = "Malformed UTF-8 characters, possibly incorrectly encoded"
|
|
1819
|
+
else:
|
|
1820
|
+
error = "Unknown JSON error occurred"
|
|
1821
|
+
|
|
1822
|
+
raise JsonDecodeException(f"JSON decode error: {error}")
|
|
1823
|
+
|
|
1824
|
+
def _check_base_url(self, baseurl: str) -> bool:
|
|
1825
|
+
"""
|
|
1826
|
+
Validate base URL format and set it
|
|
1827
|
+
"""
|
|
1828
|
+
if not re.match(r'^https?://', baseurl):
|
|
1829
|
+
raise InvalidBaseUrlException(f"Invalid base url {baseurl}")
|
|
1830
|
+
self._baseurl = baseurl
|
|
1831
|
+
return True
|
|
1832
|
+
|
|
1833
|
+
def generate_backup(self, days: int = -1):
|
|
1834
|
+
"""Generate a controller backup for the past N days."""
|
|
1835
|
+
payload = {'cmd': 'backup', 'days': days}
|
|
1836
|
+
result = self.fetch_results(f"/proxy/network/api/s/{self._site}/cmd/backup", payload=payload, prefix_path=False, boolean=False)
|
|
1837
|
+
print(f"RAW RESULT FROM FETCH_RESULTS(): {result}")
|
|
1838
|
+
return result
|
|
1839
|
+
|
|
1840
|
+
def download_backup(self, filepath: str):
|
|
1841
|
+
"""Download a generated backup file."""
|
|
1842
|
+
#with open(filepath, 'rb') as f:
|
|
1843
|
+
# return f.read()
|
|
1844
|
+
return self.exec_curl(filepath)
|
|
1845
|
+
|
|
1846
|
+
def restore_backup(self, filename: str):
|
|
1847
|
+
"""
|
|
1848
|
+
Restore a contorller backup (.unf) that already exists on the controller
|
|
1849
|
+
"""
|
|
1850
|
+
payload = {
|
|
1851
|
+
'cmd': 'restore-backup',
|
|
1852
|
+
'file': filename
|
|
1853
|
+
}
|
|
1854
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/backup", payload=payload, prefix_path=True)
|
|
1855
|
+
|
|
1856
|
+
def generate_backup_site(self):
|
|
1857
|
+
"""Generate a site export backup."""
|
|
1858
|
+
payload = {'cmd': 'export-site'}
|
|
1859
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/backup", payload=payload)
|
|
1860
|
+
|
|
1861
|
+
def list_portforwarding(self):
|
|
1862
|
+
"""Fetch port forwarding settings"""
|
|
1863
|
+
return self.fetch_results(f"/api/s/{self._site}/list/portforward")
|
|
1864
|
+
|
|
1865
|
+
def list_portforward_stats(self):
|
|
1866
|
+
"""Fetch port forwarding stats"""
|
|
1867
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/portforward")
|
|
1868
|
+
|
|
1869
|
+
def list_extension(self):
|
|
1870
|
+
"""Fetch VoIP extensions"""
|
|
1871
|
+
return self.fetch_results(f"/api/s/{self._site}/list/extension")
|
|
1872
|
+
|
|
1873
|
+
def list_settings(self):
|
|
1874
|
+
"""Fetch site settings"""
|
|
1875
|
+
return self.fetch_results(f"/api/s/{self._site}/get/setting")
|
|
1876
|
+
|
|
1877
|
+
def adopt_device(self, macs):
|
|
1878
|
+
"""Adopt one or more devices to the current site"""
|
|
1879
|
+
payload = {'cmd': 'adopt', 'macs': [m.lower() for m in (macs if isinstance(macs, list) else [macs])]}
|
|
1880
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr", payload=payload)
|
|
1881
|
+
|
|
1882
|
+
def advanced_adopt_device(
|
|
1883
|
+
self,
|
|
1884
|
+
mac: str,
|
|
1885
|
+
ip: str,
|
|
1886
|
+
username: str,
|
|
1887
|
+
password: str,
|
|
1888
|
+
url: str,
|
|
1889
|
+
port: int = 22,
|
|
1890
|
+
ssh_key_verify: bool = True
|
|
1891
|
+
) -> bool:
|
|
1892
|
+
"""Advanced SSH-based device adoption"""
|
|
1893
|
+
payload = {
|
|
1894
|
+
'cmd': 'adv-adopt',
|
|
1895
|
+
'mac': mac.lower(),
|
|
1896
|
+
'ip': ip,
|
|
1897
|
+
'username': username,
|
|
1898
|
+
'password': password,
|
|
1899
|
+
'url': url,
|
|
1900
|
+
'port': port,
|
|
1901
|
+
'sshKeyVerify': ssh_key_verify,
|
|
1902
|
+
}
|
|
1903
|
+
return self.fetch_results_boolean(
|
|
1904
|
+
f"/api/s/{self._site}/cmd/devmgr",
|
|
1905
|
+
payload=payload
|
|
1906
|
+
)
|
|
1907
|
+
|
|
1908
|
+
def restart_device(self, macs, reboot_type: str = 'soft') -> bool:
|
|
1909
|
+
"""Restart one or more devices with optional reboot type ('soft' or 'hard')"""
|
|
1910
|
+
mac_list = [m.lower() for m in (macs if isinstance(macs, list) else [macs])]
|
|
1911
|
+
payload = {'cmd': 'restart', 'macs': mac_list}
|
|
1912
|
+
if reboot_type and reboot_type.lower() in ['soft', 'hard']:
|
|
1913
|
+
payload['reboot_type'] = reboot_type.lower()
|
|
1914
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr", payload=payload)
|
|
1915
|
+
|
|
1916
|
+
def list_dynamicdns(self):
|
|
1917
|
+
"""Fetch dynamic DNS settings"""
|
|
1918
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/dynamicdns")
|
|
1919
|
+
|
|
1920
|
+
def create_dynamicdns(self, payload: dict) -> bool:
|
|
1921
|
+
"""Create dynamic DNS settings"""
|
|
1922
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/rest/dynamicdns", payload=payload)
|
|
1923
|
+
|
|
1924
|
+
def set_dynamicdns(self, dynamicdns_id: str, payload: dict) -> bool:
|
|
1925
|
+
"""Update site dynamic DNS settings"""
|
|
1926
|
+
self._curl_method = 'PUT'
|
|
1927
|
+
result = self.fetch_results_boolean(f"/api/s/{self._site}/rest/dynamicdns/{dynamicdns_id.strip()}", payload=payload)
|
|
1928
|
+
self._curl_method = 'GET'
|
|
1929
|
+
return result
|
|
1930
|
+
|
|
1931
|
+
def list_dns_records(self) -> list:
|
|
1932
|
+
return self.fetch_results(f'/v2/api/site/{self._site}/static-dns')
|
|
1933
|
+
|
|
1934
|
+
def create_dns_record(self, record_type: str, value: str, key: str, ttl: int = None, enabled: bool = True) -> dict:
|
|
1935
|
+
if record_type not in ['A', 'AAAA', 'MX', 'TXT', 'SRV', 'NS']:
|
|
1936
|
+
raise Exception(f'Invalid record type: {record_type}')
|
|
1937
|
+
|
|
1938
|
+
payload = {
|
|
1939
|
+
'record_type': record_type,
|
|
1940
|
+
'value': value,
|
|
1941
|
+
'key': key,
|
|
1942
|
+
'enabled': enabled
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
if ttl is not None:
|
|
1946
|
+
payload['ttl'] = ttl
|
|
1947
|
+
|
|
1948
|
+
return self.fetch_results(f'/v2/api/site/{self._site}/static-dns', payload=payload)
|
|
1949
|
+
|
|
1950
|
+
def delete_dns_record(self, record_id: str) -> bool:
|
|
1951
|
+
self._curl_method = "DELETE"
|
|
1952
|
+
|
|
1953
|
+
return self.fetch_results_boolean(f'/v2/api/site/{self._site}/static-dns/{record_id}')
|
|
1954
|
+
|
|
1955
|
+
def list_device_states(self) -> list:
|
|
1956
|
+
return {
|
|
1957
|
+
0: 'offline',
|
|
1958
|
+
1: 'connected',
|
|
1959
|
+
2: 'pending adoption',
|
|
1960
|
+
4: 'updating',
|
|
1961
|
+
5: 'provisioning',
|
|
1962
|
+
6: 'unreachable',
|
|
1963
|
+
7: 'adopting',
|
|
1964
|
+
9: 'adoption error',
|
|
1965
|
+
10: 'adoption failed',
|
|
1966
|
+
11: 'isolated'
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
def list_rogueaps(self, within: int = 24):
|
|
1970
|
+
"""Fetch rogue/neighboring access points"""
|
|
1971
|
+
payload = {'within': within}
|
|
1972
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/rogueap", payload=payload)
|
|
1973
|
+
|
|
1974
|
+
def extend_guest_validity(self, guest_id: str) -> bool:
|
|
1975
|
+
"""Extend guest authorization"""
|
|
1976
|
+
payload = {'_id': guest_id, 'cmd': 'extend'}
|
|
1977
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/hotspot", payload=payload)
|
|
1978
|
+
|
|
1979
|
+
def list_current_channels(self):
|
|
1980
|
+
"""Fetch current channels"""
|
|
1981
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/current-channel")
|
|
1982
|
+
|
|
1983
|
+
def migrate_device(self, macs, inform_url: str) -> bool:
|
|
1984
|
+
"""Migrate one or more devices to new inform URL."""
|
|
1985
|
+
payload = {'cmd': 'migrate', 'inform_url': inform_url, 'macs': [m.lower() for m in (macs if isinstance(macs, list) else [macs])]}
|
|
1986
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr", payload=payload)
|
|
1987
|
+
|
|
1988
|
+
def cancel_migrate_device(self, macs) -> bool:
|
|
1989
|
+
"""Cancel migration for one or more devices."""
|
|
1990
|
+
payload = {'cmd': 'cancel-migrate', 'macs': [m.lower() for m in (macs if isinstance(macs, list) else [macs])]}
|
|
1991
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr", payload=payload)
|
|
1992
|
+
|
|
1993
|
+
def force_provision(self, mac) -> bool:
|
|
1994
|
+
"""Force provision one or more devices."""
|
|
1995
|
+
payload = {'cmd': 'force-provision', 'macs': [m.lower() for m in (mac if isinstance(mac, list) else [mac])]}
|
|
1996
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr/", payload=payload)
|
|
1997
|
+
|
|
1998
|
+
def reboot_cloudkey(self) -> bool:
|
|
1999
|
+
"""Reboot a UniFi CloudKey."""
|
|
2000
|
+
payload = {'cmd': 'reboot'}
|
|
2001
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/system", payload=payload)
|
|
2002
|
+
|
|
2003
|
+
def disable_ap(self, ap_id: str, disable: bool) -> bool:
|
|
2004
|
+
"""Disable or enable an access point."""
|
|
2005
|
+
self._curl_method = 'PUT'
|
|
2006
|
+
payload = {'disabled': disable}
|
|
2007
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/rest/device/{ap_id.strip()}", payload=payload)
|
|
2008
|
+
|
|
2009
|
+
def led_override(self, device_id: str, override_mode: str) -> bool:
|
|
2010
|
+
"""Override LED mode for a device: 'off', 'on', or 'default'."""
|
|
2011
|
+
if override_mode not in ['off', 'on', 'default']:
|
|
2012
|
+
return False
|
|
2013
|
+
self._curl_method = 'PUT'
|
|
2014
|
+
payload = {'led_override': override_mode}
|
|
2015
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/rest/device/{device_id.strip()}", payload=payload)
|
|
2016
|
+
|
|
2017
|
+
def locate_ap(self, mac: str, enable: bool) -> bool:
|
|
2018
|
+
"""Toggle AP locate LED on or off."""
|
|
2019
|
+
cmd = 'set-locate' if enable else 'unset-locate'
|
|
2020
|
+
payload = {'cmd': cmd, 'mac': mac.lower()}
|
|
2021
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr", payload=payload)
|
|
2022
|
+
|
|
2023
|
+
def site_leds(self, enable: bool) -> bool:
|
|
2024
|
+
"""Toggle LEDs of all access points on or off."""
|
|
2025
|
+
payload = {'led_enabled': enable}
|
|
2026
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/set/setting/mgmt", payload=payload)
|
|
2027
|
+
|
|
2028
|
+
def custom_api_request(self, path: str, method: str = 'GET', payload=None, return_type: str = 'array', prefix_path: bool = False):
|
|
2029
|
+
"""Execute custom API request with optional boolean or array return."""
|
|
2030
|
+
if method not in self.CURL_METHODS_ALLOWED:
|
|
2031
|
+
return False
|
|
2032
|
+
if not path.startswith('/'):
|
|
2033
|
+
return False
|
|
2034
|
+
self._curl_method = method
|
|
2035
|
+
if return_type == 'array':
|
|
2036
|
+
return self.fetch_results(path, payload, prefix_path)
|
|
2037
|
+
if return_type == 'boolean':
|
|
2038
|
+
return self.fetch_results_boolean(path, payload, prefix_path)
|
|
2039
|
+
return False
|
|
2040
|
+
|
|
2041
|
+
def get_cookie(self) -> str:
|
|
2042
|
+
return self._cookies
|
|
2043
|
+
|
|
2044
|
+
def get_cookies(self) -> str:
|
|
2045
|
+
return self._cookies
|
|
2046
|
+
|
|
2047
|
+
def get_cookies_created_at(self) -> int:
|
|
2048
|
+
return self._cookies_created_at
|
|
2049
|
+
|
|
2050
|
+
def __construct(
|
|
2051
|
+
self,
|
|
2052
|
+
user: str,
|
|
2053
|
+
password: str,
|
|
2054
|
+
baseurl: str = 'https://127.0.0.1:8443',
|
|
2055
|
+
site: str = 'default',
|
|
2056
|
+
version: str = '8.0.28',
|
|
2057
|
+
ssl_verify: bool = False,
|
|
2058
|
+
unificookie_name: str = 'unificookie'
|
|
2059
|
+
):
|
|
2060
|
+
"""
|
|
2061
|
+
PHP constructor conversion: checks and initial assignments.
|
|
2062
|
+
"""
|
|
2063
|
+
# Ensure HTTP client available
|
|
2064
|
+
self._check_curl()
|
|
2065
|
+
# Validate base URL and site
|
|
2066
|
+
self._check_base_url(baseurl)
|
|
2067
|
+
self._check_site(site)
|
|
2068
|
+
|
|
2069
|
+
# Assign core properties
|
|
2070
|
+
self._baseurl = baseurl.strip()
|
|
2071
|
+
self._site = site.strip().lower()
|
|
2072
|
+
self._user = user.strip()
|
|
2073
|
+
self._password = password.strip()
|
|
2074
|
+
self._version = version.strip()
|
|
2075
|
+
self._unificookie_name = unificookie_name.strip()
|
|
2076
|
+
|
|
2077
|
+
# SSL verification settings
|
|
2078
|
+
self._verify_ssl_cert = ssl_verify
|
|
2079
|
+
|
|
2080
|
+
def __destruct(self):
|
|
2081
|
+
"""
|
|
2082
|
+
PHP destructor: if the unificookie is set in session, skip logout; otherwise logout if logged in.
|
|
2083
|
+
"""
|
|
2084
|
+
# If the unificookie is present in session cookies, skip logout
|
|
2085
|
+
if self._unificookie_name in self._session.cookies.get_dict():
|
|
2086
|
+
return
|
|
2087
|
+
|
|
2088
|
+
# Logout if still logged in
|
|
2089
|
+
if getattr(self, '_is_loggedin', False):
|
|
2090
|
+
try:
|
|
2091
|
+
self.logout()
|
|
2092
|
+
except Exception:
|
|
2093
|
+
pass
|
|
2094
|
+
|
|
2095
|
+
def list_firewallgroups(self, group_id: str = ''):
|
|
2096
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/firewallgroup/{group_id.strip()}")
|
|
2097
|
+
|
|
2098
|
+
def create_firewallgroup(self, group_name: str, group_type: str, group_members: list = []) -> bool:
|
|
2099
|
+
"""Create a new firewall group"""
|
|
2100
|
+
# Only allow specific group types
|
|
2101
|
+
if group_type not in ['address-group', 'ipv6-address-group', 'port-group']:
|
|
2102
|
+
return False
|
|
2103
|
+
payload = {
|
|
2104
|
+
'name': group_name,
|
|
2105
|
+
'group_type': group_type,
|
|
2106
|
+
'group_members': group_members
|
|
2107
|
+
}
|
|
2108
|
+
return self._request(
|
|
2109
|
+
f"/api/s/{self._site}/rest/firewallgroup",
|
|
2110
|
+
method='POST',
|
|
2111
|
+
payload=payload
|
|
2112
|
+
)
|
|
2113
|
+
|
|
2114
|
+
def edit_firewallgroup(self, group_id: str, site_id: str, group_name: str, group_type: str, group_members: list = []) -> bool:
|
|
2115
|
+
"""Edit an existing firewall group"""
|
|
2116
|
+
# Only allow specific group types
|
|
2117
|
+
if group_type not in ['address-group', 'ipv6-address-group', 'port-group']:
|
|
2118
|
+
return False
|
|
2119
|
+
# Prepare payload
|
|
2120
|
+
payload = {
|
|
2121
|
+
'_id': group_id,
|
|
2122
|
+
'name': group_name,
|
|
2123
|
+
'group_type': group_type,
|
|
2124
|
+
'group_members': group_members,
|
|
2125
|
+
'site_id': site_id
|
|
2126
|
+
}
|
|
2127
|
+
return self._request(
|
|
2128
|
+
f"/api/s/{self._site}/rest/firewallgroup/{group_id.strip()}",
|
|
2129
|
+
method='PUT',
|
|
2130
|
+
payload=payload
|
|
2131
|
+
)
|
|
2132
|
+
|
|
2133
|
+
def delete_firewallgroup(self, group_id: str) -> bool:
|
|
2134
|
+
self._curl_method = "DELETE"
|
|
2135
|
+
return self.fetch_results_boolean(f'/api/s/{self._site}/rest/firewallgroup/{group_id.strip()}')
|
|
2136
|
+
self._curl_method = "GET"
|
|
2137
|
+
|
|
2138
|
+
def list_firewallrules(self):
|
|
2139
|
+
return self._request(f"/api/s/{self._site}/rest/firewallrule")
|
|
2140
|
+
|
|
2141
|
+
def list_routing(self, route_id: str = ''):
|
|
2142
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/routing/{route_id.strip()}")
|
|
2143
|
+
|
|
2144
|
+
def set_tagged_devices(self, macs: list, tag_id: str) -> bool:
|
|
2145
|
+
self._curl_method = "PUT"
|
|
2146
|
+
payload = {'member_table': macs}
|
|
2147
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/rest/tag/{tag_id}", payload=payload)
|
|
2148
|
+
|
|
2149
|
+
def set_ap_radiosettings(self, ap_id: str, radio: str, channel: int, ht: int, tx_power_mode: str, tx_power: int) -> bool:
|
|
2150
|
+
"""Set AP radio settings"""
|
|
2151
|
+
payload = {
|
|
2152
|
+
'radio_table': {
|
|
2153
|
+
'radio': radio,
|
|
2154
|
+
'channel': channel,
|
|
2155
|
+
'ht': ht,
|
|
2156
|
+
'tx_power_mode': tx_power_mode,
|
|
2157
|
+
'tx_power': tx_power,
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
return self.fetch_results_boolean(
|
|
2161
|
+
f"/api/s/{self._site}/upd/device/{ap_id.strip()}",
|
|
2162
|
+
payload=payload
|
|
2163
|
+
)
|
|
2164
|
+
|
|
2165
|
+
def set_ap_wlangroup(self, type_id: str, device_id: str, group_id: str) -> bool:
|
|
2166
|
+
"""Assign AP to WLAN group based on radio type 'ng' or 'na'"""
|
|
2167
|
+
# Only allow specific radio types
|
|
2168
|
+
if type_id not in ['ng', 'na']:
|
|
2169
|
+
return False
|
|
2170
|
+
payload = {
|
|
2171
|
+
'wlan_overrides': [],
|
|
2172
|
+
f'wlangroup_id_{type_id}': group_id
|
|
2173
|
+
}
|
|
2174
|
+
return self.fetch_results_boolean(
|
|
2175
|
+
f"/api/s/{self._site}/upd/device/{device_id.strip()}",
|
|
2176
|
+
payload=payload
|
|
2177
|
+
)
|
|
2178
|
+
|
|
2179
|
+
def set_guestlogin_settings_base(self, payload: dict, section_id: str = '') -> bool:
|
|
2180
|
+
"""Update guest login settings, base. Applies to a specific section if section_id provided."""
|
|
2181
|
+
# Append section_id to path if given
|
|
2182
|
+
suffix = f"/{section_id}" if section_id else ''
|
|
2183
|
+
return self.fetch_results_boolean(
|
|
2184
|
+
f"/api/s/{self._site}/set/setting/guest_access{suffix}",
|
|
2185
|
+
payload=payload
|
|
2186
|
+
)
|
|
2187
|
+
|
|
2188
|
+
def set_guestlogin_settings(
|
|
2189
|
+
self,
|
|
2190
|
+
portal_enabled: bool,
|
|
2191
|
+
portal_customized: bool,
|
|
2192
|
+
redirect_enabled: bool,
|
|
2193
|
+
redirect_url: str,
|
|
2194
|
+
x_password: str,
|
|
2195
|
+
expire_number: int,
|
|
2196
|
+
expire_unit: int,
|
|
2197
|
+
section_id: str
|
|
2198
|
+
) -> bool:
|
|
2199
|
+
"""Configure guest login settings with full options."""
|
|
2200
|
+
payload = {
|
|
2201
|
+
'portal_enabled': portal_enabled,
|
|
2202
|
+
'portal_customized': portal_customized,
|
|
2203
|
+
'redirect_enabled': redirect_enabled,
|
|
2204
|
+
'redirect_url': redirect_url,
|
|
2205
|
+
'x_password': x_password,
|
|
2206
|
+
'expire_number': expire_number,
|
|
2207
|
+
'expire_unit': expire_unit,
|
|
2208
|
+
'_id': section_id,
|
|
2209
|
+
}
|
|
2210
|
+
return self.fetch_results_boolean(
|
|
2211
|
+
f"/api/s/{self._site}/set/setting/guest_access/{section_id}",
|
|
2212
|
+
payload=payload
|
|
2213
|
+
)
|
|
2214
|
+
|
|
2215
|
+
def set_guestlogin_settings_base(self, payload: dict, section_id: str = '') -> bool:
|
|
2216
|
+
"""Update guest login settings, base. Applies to a specific section if section_id provided."""
|
|
2217
|
+
suffix = f"/{section_id}" if section_id else ''
|
|
2218
|
+
return self.fetch_results_boolean(
|
|
2219
|
+
f"/api/s/{self._site}/set/setting/guest_access{suffix}",
|
|
2220
|
+
payload=payload
|
|
2221
|
+
)
|
|
2222
|
+
|
|
2223
|
+
def set_ips_settings_base(self, payload: dict) -> bool:
|
|
2224
|
+
"""Update IPS/IDS settings, base."""
|
|
2225
|
+
return self.fetch_results_boolean(
|
|
2226
|
+
f"/api/s/{self._site}/set/setting/ips",
|
|
2227
|
+
payload=payload
|
|
2228
|
+
)
|
|
2229
|
+
|
|
2230
|
+
def set_super_mgmt_settings_base(self, settings_id: str, payload: dict) -> bool:
|
|
2231
|
+
"""Update "Super Management" settings, base."""
|
|
2232
|
+
return self.fetch_results_boolean(
|
|
2233
|
+
f"/api/s/{self._site}/set/setting/super_mgmt/{settings_id.strip()}",
|
|
2234
|
+
payload=payload
|
|
2235
|
+
)
|
|
2236
|
+
|
|
2237
|
+
def set_super_smtp_settings_base(self, settings_id: str, payload: dict) -> bool:
|
|
2238
|
+
"""Update "Super SMTP" settings, base."""
|
|
2239
|
+
return self.fetch_results_boolean(
|
|
2240
|
+
f"/api/s/{self._site}/set/setting/super_smtp/{settings_id.strip()}",
|
|
2241
|
+
payload=payload
|
|
2242
|
+
)
|
|
2243
|
+
|
|
2244
|
+
def set_super_identity_settings_base(self, settings_id: str, payload: dict) -> bool:
|
|
2245
|
+
"""Update "Super Controller Identity" settings, base."""
|
|
2246
|
+
return self.fetch_results_boolean(
|
|
2247
|
+
f"/api/s/{self._site}/set/setting/super_identity/{settings_id.strip()}",
|
|
2248
|
+
payload=payload
|
|
2249
|
+
)
|
|
2250
|
+
|
|
2251
|
+
def rename_ap(self, ap_id: str, ap_name: str) -> bool:
|
|
2252
|
+
payload = {'name': ap_name}
|
|
2253
|
+
return self.fetch_results_boolean(f'/api/s/{self._site}/upd/device/{ap_id.strip()}', payload=payload)
|
|
2254
|
+
|
|
2255
|
+
def move_device(self, mac: str, site_id: str) -> bool:
|
|
2256
|
+
"""Move a device to another site"""
|
|
2257
|
+
payload = {'cmd': 'move-device', 'site': site_id, 'mac': mac.lower()}
|
|
2258
|
+
return self.fetch_results_boolean(
|
|
2259
|
+
f"/api/s/{self._site}/cmd/sitemgr",
|
|
2260
|
+
payload=payload
|
|
2261
|
+
)
|
|
2262
|
+
|
|
2263
|
+
def delete_device(self, mac: str) -> bool:
|
|
2264
|
+
payload = {'cmd': 'delete-device', 'mac': mac.lower()}
|
|
2265
|
+
|
|
2266
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
2267
|
+
|
|
2268
|
+
def check_firmware_update(self) -> bool:
|
|
2269
|
+
payload = {'cmd': 'check-firmware-update'}
|
|
2270
|
+
|
|
2271
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/productinfo", payload=payload)
|
|
2272
|
+
|
|
2273
|
+
def upgrade_device(self, mac: str) -> bool:
|
|
2274
|
+
payload = {'mac': mac.lower()}
|
|
2275
|
+
|
|
2276
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr/upgrade", payload=payload)
|
|
2277
|
+
|
|
2278
|
+
def upgrade_all_devices(self, type: str = 'uap') -> bool:
|
|
2279
|
+
payload = {'type': type.lower()}
|
|
2280
|
+
|
|
2281
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr/upgrade-all", payload=payload)
|
|
2282
|
+
|
|
2283
|
+
def upgrade_device_external(self, firmware_url: str, macs: list) -> bool:
|
|
2284
|
+
"""Upgrade devices using an external firmware URL and list of MAC addresses"""
|
|
2285
|
+
# Sanitize URL and normalize MACs
|
|
2286
|
+
sanitized_url = firmware_url.strip()
|
|
2287
|
+
macs_list = [m.lower() for m in macs]
|
|
2288
|
+
payload = {
|
|
2289
|
+
'url': sanitized_url,
|
|
2290
|
+
'macs': macs_list
|
|
2291
|
+
}
|
|
2292
|
+
return self.fetch_results_boolean(
|
|
2293
|
+
f"/api/s/{self._site}/cmd/devmgr/upgrade-external",
|
|
2294
|
+
payload=payload
|
|
2295
|
+
)
|
|
2296
|
+
|
|
2297
|
+
def start_rolling_upgrade(self, payload: list = {'uap', 'usw', 'ugw', 'uxg'}) -> bool:
|
|
2298
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr/set-rollupgrade", payload=payload)
|
|
2299
|
+
|
|
2300
|
+
def cancel_rolling_upgrade(self) -> bool:
|
|
2301
|
+
payload = {"cmd": "unset-rollupgrade"}
|
|
2302
|
+
|
|
2303
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/devmgr", payload=payload)
|
|
2304
|
+
|
|
2305
|
+
def list_firmware(self, type: str="available"):
|
|
2306
|
+
if type not in ['available', 'cached']:
|
|
2307
|
+
return False
|
|
2308
|
+
|
|
2309
|
+
payload = {'cmd': f'list-{type}'}
|
|
2310
|
+
|
|
2311
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/firmware", payload=payload)
|
|
2312
|
+
|
|
2313
|
+
def get_debug(self) -> bool:
|
|
2314
|
+
return getattr(self, 'debug', False)
|
|
2315
|
+
|
|
2316
|
+
def fetch_results(
|
|
2317
|
+
self,
|
|
2318
|
+
path: str,
|
|
2319
|
+
payload = None,
|
|
2320
|
+
boolean: bool = False,
|
|
2321
|
+
login_required: bool = False,
|
|
2322
|
+
prefix_path: bool = False
|
|
2323
|
+
):
|
|
2324
|
+
if login_required and not self._is_loggedin:
|
|
2325
|
+
raise LoginRequiredException()
|
|
2326
|
+
|
|
2327
|
+
self._last_results_raw = self.exec_curl(path, payload, prefix_path)
|
|
2328
|
+
self._last_results_raw = self._last_results_raw.decode()
|
|
2329
|
+
|
|
2330
|
+
if isinstance(self._last_results_raw, str):
|
|
2331
|
+
try:
|
|
2332
|
+
response = json.loads(self._last_results_raw)
|
|
2333
|
+
print("Fetched response:", response)
|
|
2334
|
+
except:
|
|
2335
|
+
self._get_json_last_error()
|
|
2336
|
+
raise
|
|
2337
|
+
|
|
2338
|
+
if isinstance(response, dict) and 'meta' in response:
|
|
2339
|
+
if response['meta'].get('rc') == 'ok':
|
|
2340
|
+
self._last_error_message = ''
|
|
2341
|
+
if 'data' in response:
|
|
2342
|
+
if isinstance(response['data'], list):
|
|
2343
|
+
print("Response inside fetch_results():", response)
|
|
2344
|
+
print("Data:", response.get("data"))
|
|
2345
|
+
return response['data'] if not boolean else True
|
|
2346
|
+
return [response['data']] if not boolean else True
|
|
2347
|
+
return True
|
|
2348
|
+
elif response['meta'].get('rc') == 'error':
|
|
2349
|
+
self._last_error_message = 'An unknown error was returned by the controller'
|
|
2350
|
+
|
|
2351
|
+
raise Exception(f"Error message: {self._last_error_message}")
|
|
2352
|
+
|
|
2353
|
+
if path.startswith('/v2/api/'):
|
|
2354
|
+
if 'errorCode' in response:
|
|
2355
|
+
self._last_error_message = 'AN unkown error was returned by an API v2 endpoind'
|
|
2356
|
+
raise Exception(f"Error code: {response['errorCode']}, message: {self.last_error_message}")
|
|
2357
|
+
return response
|
|
2358
|
+
|
|
2359
|
+
# UniFi OS response
|
|
2360
|
+
if path.startswith('/api/'):
|
|
2361
|
+
if 'code' in response:
|
|
2362
|
+
self._last_error_message = response.get('message', 'An unknown error was returned by a UniFi OS endpoint.')
|
|
2363
|
+
raise Exception(f"Error code: {response['code']}, message: {self._last_error_message}")
|
|
2364
|
+
if not boolean:
|
|
2365
|
+
return [response]
|
|
2366
|
+
return True
|
|
2367
|
+
return False
|
|
2368
|
+
|
|
2369
|
+
def fetch_results_boolean(
|
|
2370
|
+
self,
|
|
2371
|
+
path: str,
|
|
2372
|
+
payload=None,
|
|
2373
|
+
login_required: bool = True,
|
|
2374
|
+
prefix_path: bool = True
|
|
2375
|
+
) -> bool:
|
|
2376
|
+
"""Call fetch_results and always return a boolean"""
|
|
2377
|
+
return self.fetch_results(path, payload, True, login_required, prefix_path)
|
|
2378
|
+
|
|
2379
|
+
def get_json_last_error(self) -> bool:
|
|
2380
|
+
"""Raise exception with message matching last JSON decoding error."""
|
|
2381
|
+
error_code = json.JSONDecodeError
|
|
2382
|
+
error_map = {
|
|
2383
|
+
0: 'No error',
|
|
2384
|
+
1: 'The maximum stack depth has been exceeded',
|
|
2385
|
+
2: 'Invalid or malformed JSON',
|
|
2386
|
+
3: 'Control character error, possibly incorrectly encoded',
|
|
2387
|
+
4: 'Syntax error, malformed JSON',
|
|
2388
|
+
5: 'Malformed UTF-8 characters, possibly incorrectly encoded',
|
|
2389
|
+
6: 'One or more recursive references in the value to be encoded',
|
|
2390
|
+
7: 'One or more NAN or INF values in the value to be encoded',
|
|
2391
|
+
8: 'A value of a type that cannot be encoded was given',
|
|
2392
|
+
9: 'A property name that cannot be encoded was given',
|
|
2393
|
+
10: 'Malformed UTF-16 characters, possibly incorrectly encoded',
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
# Attempt to find error from last decoding (simulate json_last_error from PHP)
|
|
2397
|
+
error = error_map.get(getattr(error_code, 'errno', None), 'Unknown JSON error occurred')
|
|
2398
|
+
raise Exception(f'JSON decode error: {error} JSON decode error: ' + error_map.get(json.JSONDecodeError, 'Unknown JSON error occurred'))
|
|
2399
|
+
|
|
2400
|
+
def check_base_url(self, baseurl: str) -> bool:
|
|
2401
|
+
parsed = urlparse(baseurl)
|
|
2402
|
+
if not all([parsed.scheme, parsed.netloc]) or baseurl.endswith("/"):
|
|
2403
|
+
raise InvalidBaseUrlException()
|
|
2404
|
+
|
|
2405
|
+
return True
|
|
2406
|
+
|
|
2407
|
+
def exec_curl(self, path: str, payload=None, prefix_path: bool = True):
|
|
2408
|
+
# 1) method sanity check
|
|
2409
|
+
if self._curl_method not in self.CURL_METHODS_ALLOWED:
|
|
2410
|
+
raise InvalidCurlMethodException()
|
|
2411
|
+
|
|
2412
|
+
# 2) build URL
|
|
2413
|
+
url = f"{self._baseurl}{path}"
|
|
2414
|
+
if self._unifi_os and prefix_path:
|
|
2415
|
+
url = f"{self._baseurl}/proxy/network{path}"
|
|
2416
|
+
|
|
2417
|
+
# 3) build curl_options dict
|
|
2418
|
+
"""
|
|
2419
|
+
curl_options = {
|
|
2420
|
+
'method': self._curl_method,
|
|
2421
|
+
'url': url,
|
|
2422
|
+
'headers': None, # filled in below
|
|
2423
|
+
'timeout': 30,
|
|
2424
|
+
'verify': self._verify_ssl_cert,
|
|
2425
|
+
}
|
|
2426
|
+
"""
|
|
2427
|
+
|
|
2428
|
+
opts = self.get_curl_handle()
|
|
2429
|
+
|
|
2430
|
+
opts.update({
|
|
2431
|
+
'method': self._curl_method,
|
|
2432
|
+
'url': url,
|
|
2433
|
+
'headers': { **opts['headers'], **self._curl_headers}
|
|
2434
|
+
})
|
|
2435
|
+
|
|
2436
|
+
# 4) handle payload
|
|
2437
|
+
json_payload = ''
|
|
2438
|
+
if payload:
|
|
2439
|
+
json_payload = json.dumps(payload, separators=(',', ':'), ensure_ascii=False)
|
|
2440
|
+
opts['data'] = json_payload
|
|
2441
|
+
|
|
2442
|
+
# force POST if GET or DELETE
|
|
2443
|
+
if self._curl_method in ('GET', 'DELETE'):
|
|
2444
|
+
self._curl_method = 'POST'
|
|
2445
|
+
opts['method'] = 'POST'
|
|
2446
|
+
|
|
2447
|
+
# 5) set custom method flags
|
|
2448
|
+
if self._curl_method == 'POST':
|
|
2449
|
+
# nothing extra; requests uses method field
|
|
2450
|
+
pass
|
|
2451
|
+
elif self._curl_method in ('DELETE', 'PUT', 'PATCH'):
|
|
2452
|
+
opts['method'] = self._curl_method
|
|
2453
|
+
|
|
2454
|
+
# 6) CSRF for UniFi OS non-GET
|
|
2455
|
+
if self._unifi_os and self._curl_method != 'GET':
|
|
2456
|
+
self.create_x_csrf_token_header()
|
|
2457
|
+
|
|
2458
|
+
# 7) attach headers last
|
|
2459
|
+
opts['headers'] = self._curl_headers
|
|
2460
|
+
|
|
2461
|
+
# 8) perform request
|
|
2462
|
+
try:
|
|
2463
|
+
opts['verify'] = False
|
|
2464
|
+
resp = self._session.request(**opts)
|
|
2465
|
+
except Timeout as e:
|
|
2466
|
+
raise CurlTimeoutException(str(e), None, None)
|
|
2467
|
+
except RequestException as e:
|
|
2468
|
+
raise CurlGeneralErrorException(f"Request error: {e}", None, None)
|
|
2469
|
+
|
|
2470
|
+
http_code = resp.status_code
|
|
2471
|
+
|
|
2472
|
+
# 9) handle expired auth
|
|
2473
|
+
if http_code == 401:
|
|
2474
|
+
if self.get_debug:
|
|
2475
|
+
print(f"exec_curl: 401 on {url}, need to re-login")
|
|
2476
|
+
if self._exec_retries == 0:
|
|
2477
|
+
# clear stored cookie/token
|
|
2478
|
+
self.cookies = ''
|
|
2479
|
+
self.cookies_created_at = 0
|
|
2480
|
+
self.is_logged_in = False
|
|
2481
|
+
self._exec_retries += 1
|
|
2482
|
+
|
|
2483
|
+
if self._session:
|
|
2484
|
+
self._session.close()
|
|
2485
|
+
# attempt re-login
|
|
2486
|
+
from time import sleep
|
|
2487
|
+
if self.login():
|
|
2488
|
+
if self.get_debug:
|
|
2489
|
+
print("exec_curl: re-login succeeded, retrying exec_curl")
|
|
2490
|
+
return self.exec_curl(path, payload, prefix_path)
|
|
2491
|
+
raise LoginFailedException('Cookie/Token expired and re-login failed.')
|
|
2492
|
+
raise LoginFailedException('Login failed, check credentials.')
|
|
2493
|
+
|
|
2494
|
+
# 10) debug dump
|
|
2495
|
+
if self.get_debug:
|
|
2496
|
+
print("\n---------cURL INFO-----------")
|
|
2497
|
+
print("Options:", opts)
|
|
2498
|
+
print("URL & PAYLOAD:", url)
|
|
2499
|
+
print("Payload:", json_payload or '<empty>')
|
|
2500
|
+
print("Response Code:", http_code)
|
|
2501
|
+
print("Response Body:", resp.text)
|
|
2502
|
+
print("-----------------------------\n")
|
|
2503
|
+
|
|
2504
|
+
# 11) reset method and retry count
|
|
2505
|
+
self._curl_method = self.DEFAULT_CURL_METHOD
|
|
2506
|
+
self._exec_retries = 0
|
|
2507
|
+
|
|
2508
|
+
return resp.content
|
|
2509
|
+
|
|
2510
|
+
def get_curl_handle(self):
|
|
2511
|
+
"""
|
|
2512
|
+
Mirror PHP's get_curl_handle():
|
|
2513
|
+
builds a curl_options dict for requests.Session.request()
|
|
2514
|
+
"""
|
|
2515
|
+
# Determine SSL verification
|
|
2516
|
+
verify_ssl = bool(self.get_curl_ssl_verify_peer and self.get_curl_ssl_verify_host)
|
|
2517
|
+
|
|
2518
|
+
# Map connect & overall timeouts
|
|
2519
|
+
curl_options = {
|
|
2520
|
+
'timeout': (self.get_connection_timeout(), self.get_curl_request_timeout()),
|
|
2521
|
+
'verify': verify_ssl,
|
|
2522
|
+
'headers': {},
|
|
2523
|
+
}
|
|
2524
|
+
|
|
2525
|
+
# Verbose logging if debug
|
|
2526
|
+
if self.get_debug:
|
|
2527
|
+
# shows per-request wire logs
|
|
2528
|
+
logging.getLogger('urllib3').setLevel(logging.DEBUG)
|
|
2529
|
+
|
|
2530
|
+
# Attach cookies if present
|
|
2531
|
+
if getattr(self, 'cookies', None):
|
|
2532
|
+
curl_options['headers']['Cookie'] = self._cookies
|
|
2533
|
+
|
|
2534
|
+
return curl_options
|
|
2535
|
+
|
|
2536
|
+
def response_header_callback(self, response: requests.Response):
|
|
2537
|
+
"""
|
|
2538
|
+
Process Set-Cookie headers to extract UniFi session or TOKEN cookie.
|
|
2539
|
+
"""
|
|
2540
|
+
cookies = []
|
|
2541
|
+
raw = getattr(response, 'raw', None)
|
|
2542
|
+
if raw and hasattr(raw, 'headers') and hasattr(raw.headers, 'get_all'):
|
|
2543
|
+
cookies = raw.headers.get_all('Set-Cookie') or []
|
|
2544
|
+
else:
|
|
2545
|
+
sc = response.headers.get('Set-Cookie')
|
|
2546
|
+
if sc:
|
|
2547
|
+
cookies = [sc]
|
|
2548
|
+
for header in cookies:
|
|
2549
|
+
for crumb in (c.strip() for c in header.split(';')):
|
|
2550
|
+
if 'unifises' in crumb:
|
|
2551
|
+
self._cookies = crumb
|
|
2552
|
+
self._cookies_created_at = int(time.time())
|
|
2553
|
+
self._is_loggedin = True
|
|
2554
|
+
self._unifi_os = False
|
|
2555
|
+
return
|
|
2556
|
+
if 'TOKEN' in crumb:
|
|
2557
|
+
self._cookies = crumb
|
|
2558
|
+
self._cookies_created_at = int(time.time())
|
|
2559
|
+
self._is_loggedin = True
|
|
2560
|
+
self._unifi_os = True
|
|
2561
|
+
return
|
|
2562
|
+
|
|
2563
|
+
def create_x_csrf_token_header(self):
|
|
2564
|
+
# 1) Do we even have a TOKEN cookie?
|
|
2565
|
+
cookies = getattr(self, 'cookies', '')
|
|
2566
|
+
if not cookies or 'TOKEN' not in cookies:
|
|
2567
|
+
return
|
|
2568
|
+
|
|
2569
|
+
# 2) Split on first '=', get the JWT
|
|
2570
|
+
parts = cookies.split('=', 1)
|
|
2571
|
+
if len(parts) < 2:
|
|
2572
|
+
return
|
|
2573
|
+
jwt = parts[1]
|
|
2574
|
+
|
|
2575
|
+
# 3) Split JWT into its three '.' parts
|
|
2576
|
+
comps = jwt.split('.')
|
|
2577
|
+
if len(comps) < 2:
|
|
2578
|
+
return
|
|
2579
|
+
payload_b64 = comps[1]
|
|
2580
|
+
|
|
2581
|
+
# 4) Pad base64 to correct length
|
|
2582
|
+
pad_len = (-len(payload_b64)) % 4
|
|
2583
|
+
if pad_len:
|
|
2584
|
+
payload_b64 = payload_b64 + ('=' * pad_len)
|
|
2585
|
+
|
|
2586
|
+
# 5) Decode base64 -> bytes, then bytes -> str
|
|
2587
|
+
try:
|
|
2588
|
+
decoded_bytes = base64.b64decode(payload_b64)
|
|
2589
|
+
decoded_str = decoded_bytes.decode('utf-8')
|
|
2590
|
+
payload_dict = json.loads(decoded_str)
|
|
2591
|
+
except Exception:
|
|
2592
|
+
return
|
|
2593
|
+
|
|
2594
|
+
# 6) Extract the token
|
|
2595
|
+
csrf_token = payload_dict.get('csrfToken')
|
|
2596
|
+
if not csrf_token:
|
|
2597
|
+
return
|
|
2598
|
+
|
|
2599
|
+
# 7) Remove any existing x-csrf-token headers (case-insensitive)
|
|
2600
|
+
filtered = []
|
|
2601
|
+
for header in self.curl_headers:
|
|
2602
|
+
if header.lower().find('x-csrf-token:') == -1:
|
|
2603
|
+
filtered.append(header)
|
|
2604
|
+
self.curl_headers = filtered
|
|
2605
|
+
|
|
2606
|
+
# 8) Append the new header, using only ASCII
|
|
2607
|
+
self.curl_headers.append('x-csrf-token: %s' % csrf_token)
|