-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunifi_climgr.py
More file actions
executable file
·6750 lines (5821 loc) · 305 KB
/
unifi_climgr.py
File metadata and controls
executable file
·6750 lines (5821 loc) · 305 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2025 netcon-sync contributors
#
# This file is part of netcon-sync.
# netcon-sync is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
"""UniFi network management CLI - comprehensive client and network management."""
import os
import sys
import argparse
import json
import time
import tarfile
import shutil
import re
from datetime import datetime, timedelta
from collections import defaultdict
from pathlib import Path
from threading import Lock
from concurrent.futures import ThreadPoolExecutor, as_completed
# Import shared modules - config might fail if env vars are missing
UNIFI_NETWORK_URL = None
UNIFI_SITE_ID = None
_config_error = None
try:
import nss.error
import paramiko
from scp import SCPClient
import unifi_utils
from config import UNIFI_NETWORK_URL, UNIFI_SITE_ID, DEFAULT_DOMAIN
from trust import handle_trust_server_url, handle_trust_ca_cert, format_nss_error, ensure_nss_db
from urllib.parse import urlparse
except ModuleNotFoundError as e:
print(f"ERROR: Missing required dependency: {e}")
print("\nPlease run the setup script:")
print(" ./install_deps.sh")
sys.exit(1)
except ValueError as e:
# Store config error - we'll show help + error in main()
_config_error = e
UNIFI_NETWORK_URL = None
UNIFI_SITE_ID = None
DEFAULT_DOMAIN = ""
# ==============================================================================
# COLUMN SCHEMAS - Centralized column definitions for clients and APs
# ==============================================================================
# Client columns
CLIENT_COLUMN_SCHEMA = {
"mac": ("MAC Address", 17),
"hostname": ("Hostname", 10),
"vendor": ("Vendor", 20),
"description": ("Description", 10),
"status": ("Status", 8),
"ip": ("IP Address", 15),
"dns_name": ("DNS Name", 10),
"uptime": ("Uptime", 12),
"connected_ap_name": ("AP", 10),
"connected_ap_mac": ("AP MAC", 10),
"channel": ("Channel", 8),
"band": ("Band", 8),
"wifi_generation": ("WiFi", 5),
"ieee_version": ("IEEE", 6),
"ssid": ("SSID", 20),
"signal": ("Signal", 7),
"retries": ("Retries", 9),
"locked": ("Locked", 7),
"locked_ap_name": ("Locked AP", 10),
"locked_ap_mac": ("Locked AP MAC", 17),
"last_seen": ("Last Seen", 11),
}
CLIENT_COLUMN_NAMES = list(CLIENT_COLUMN_SCHEMA.keys())
# Default columns for client listing (used when no +/- switches provided)
DEFAULT_CLIENT_COLUMNS = ["description", "mac", "status", "last_seen", "ip", "connected_ap_name", "signal", "locked"]
# AP columns
AP_COLUMN_SCHEMA = {
"name": ("Device Name", 15),
"mac": ("MAC Address", 17),
"ip": ("IP Address", 15),
"version": ("Firmware", 10),
"uptime": ("Uptime", 12),
"state": ("State", 20),
"connection": ("Connection", 10),
"enabled": ("Enabled", 9),
"uplink_ap_name": ("Uplink AP Name", 15),
"uplink_ap_mac": ("Uplink AP MAC", 17),
}
AP_COLUMN_NAMES = list(AP_COLUMN_SCHEMA.keys())
# SSID columns
SSID_COLUMN_SCHEMA = {
"name": ("SSID Name", 20),
"enabled": ("Enabled", 9),
"security": ("Security", 10),
"band": ("Band", 15),
}
SSID_COLUMN_NAMES = list(SSID_COLUMN_SCHEMA.keys())
# Legacy reference for backward compatibility
COLUMN_SCHEMA = CLIENT_COLUMN_SCHEMA
ALL_COLUMN_NAMES = CLIENT_COLUMN_NAMES
# ==============================================================================
# AP LOG COLLECTION FUNCTIONS
# ==============================================================================
# Thread-safe print lock for parallel operations
print_lock = Lock()
def get_ssh_credentials():
"""
Retrieve SSH credentials from UniFi controller.
Returns:
tuple: (username, password) or (None, None) if not found
"""
endpoint = f"/api/s/{UNIFI_SITE_ID}/rest/setting/mgmt"
try:
settings = unifi_utils.make_unifi_api_call("GET", endpoint)
if isinstance(settings, dict) and 'data' in settings:
settings = settings['data']
if isinstance(settings, list) and len(settings) > 0:
mgmt_settings = settings[0]
username = mgmt_settings.get('x_ssh_username', 'ubnt')
password = mgmt_settings.get('x_ssh_password', '')
if username and password:
print("[OK] Retrieved SSH credentials")
return username, password
except Exception as e:
print(f"Warning: Could not retrieve SSH credentials from settings: {e}")
# Fallback: try sysinfo endpoint
endpoint = f"/api/s/{UNIFI_SITE_ID}/stat/sysinfo"
try:
sysinfo = unifi_utils.make_unifi_api_call("GET", endpoint)
if isinstance(sysinfo, dict) and 'data' in sysinfo:
sysinfo_data = sysinfo['data'][0] if isinstance(sysinfo['data'], list) else sysinfo['data']
username = sysinfo_data.get('x_ssh_username', 'ubnt')
password = sysinfo_data.get('x_ssh_password', '')
if username and password:
print("[OK] Retrieved SSH credentials from sysinfo")
return username, password
except Exception as e:
print(f"Warning: Could not retrieve SSH credentials from sysinfo: {e}")
return None, None
def collect_ap_support_bundle(ssh_client, ap_name):
"""
Generate support bundle on AP using 'supp' command.
Args:
ssh_client: Active SSH client connection
ap_name: AP name for logging
Returns:
tuple: (success, bundle_path, size_str) or (False, None, None)
"""
try:
print(f"[{ap_name}] Generating support info bundle...")
print(f"[{ap_name}] Trying 'supp' command...")
start_time = time.time()
stdin, stdout, stderr = ssh_client.exec_command('supp', timeout=120)
output = stdout.read().decode('utf-8', errors='replace')
stderr.read() # Consume stderr
elapsed = time.time() - start_time
print(f"[{ap_name}] supp command took {elapsed:.1f} seconds")
# Check if file exists
stdin, stdout, stderr = ssh_client.exec_command('ls -lh /tmp/support.tgz')
ls_stdout = stdout.read().decode('utf-8')
if 'support.tgz' in ls_stdout:
size_match = re.search(r'(\d+(?:\.\d+)?[KMG]?)\s+\w+\s+\d+\s+[\d:]+\s+/tmp/support\.tgz', ls_stdout)
size_str = size_match.group(1) if size_match else 'unknown size'
print(f"[{ap_name}] [OK] Support bundle generated: /tmp/support.tgz ({size_str})")
return True, '/tmp/support.tgz', size_str
else:
print(f"[{ap_name}] supp: file not found after command completed")
return False, None, None
except Exception as e:
print(f"[{ap_name}] supp command failed: {e}")
return False, None, None
def collect_logs_from_ap(ap_ip, ap_name, ap_mac, ssh_username, ssh_password, output_dir, timeout=60):
"""
Collect diagnostic logs from a single AP via SSH/SCP.
Args:
ap_ip: AP IP address
ap_name: AP display name
ap_mac: AP MAC address
ssh_username: SSH username
ssh_password: SSH password
output_dir: Local directory to save files
timeout: SSH timeout in seconds
Returns:
dict: Collection result with success status, files, errors, timing
"""
result = {
'success': False,
'ap_name': ap_name,
'ap_mac': ap_mac,
'ap_ip': ap_ip,
'files': [],
'error': None,
'elapsed_time': 0,
'start_timestamp': None,
'end_timestamp': None
}
ssh_client = None
start_time = time.time()
start_timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
result['start_timestamp'] = start_timestamp
# Create AP-specific directory
safe_ap_name = ap_name.replace('/', '_').replace(' ', '_')
ap_dir = output_dir / f"{safe_ap_name}_{ap_mac.replace(':', '-')}"
ap_dir.mkdir(parents=True, exist_ok=True)
try:
with print_lock:
print(f"\n{'='*60}")
print(f"[{ap_name}] [{start_timestamp}] Connecting to {ap_ip}...")
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh_client.connect(
hostname=ap_ip,
username=ssh_username,
password=ssh_password,
timeout=timeout,
allow_agent=False,
look_for_keys=False,
banner_timeout=30 # Increase banner timeout for slow APs
)
except paramiko.ssh_exception.AuthenticationException as e:
result['error'] = f"Authentication failed: {e}"
with print_lock:
print(f"[{ap_name}] [FAIL] Authentication failed")
print(f"[{ap_name}] Check: Settings > System > Advanced > Device SSH Authentication")
return result
except paramiko.ssh_exception.NoValidConnectionsError as e:
result['error'] = f"SSH connection refused: {e}"
with print_lock:
print(f"[{ap_name}] [FAIL] SSH connection refused on port 22")
print(f"[{ap_name}] Possible causes:")
print(f"[{ap_name}] - SSH not enabled on controller")
print(f"[{ap_name}] - AP firmware doesn't support SSH")
print(f"[{ap_name}] - Firewall blocking port 22")
return result
except paramiko.ssh_exception.SSHException as e:
result['error'] = f"SSH protocol error: {e}"
with print_lock:
print(f"[{ap_name}] [FAIL] SSH protocol error: {e}")
return result
except Exception as e:
result['error'] = f"SSH connection error: {e}"
with print_lock:
print(f"[{ap_name}] [FAIL] SSH connection error: {e}")
return result
with print_lock:
print(f"[{ap_name}] [OK] Connected")
# Generate support bundle
success, bundle_path, size_str = collect_ap_support_bundle(ssh_client, ap_name)
if success and bundle_path:
# Download via SCP
local_path = ap_dir / Path(bundle_path).name
with print_lock:
print(f"[{ap_name}] Downloading {Path(bundle_path).name} ({size_str})...", end="", flush=True)
try:
with SCPClient(ssh_client.get_transport()) as scp:
scp.get(bundle_path, str(local_path))
actual_size = local_path.stat().st_size
with print_lock:
print(f" [OK]")
result['files'].append({
'remote_path': bundle_path,
'local_path': str(local_path),
'size': actual_size,
'type': 'support_bundle'
})
# Clean up remote file
try:
stdin, stdout, stderr = ssh_client.exec_command(f'rm -f {bundle_path}')
stdout.read()
except:
pass
except Exception as e:
with print_lock:
print(f" [FAIL]: {e}")
# Collect log files from /var/log/
with print_lock:
print(f"[{ap_name}] Collecting individual log files...")
stdin, stdout, stderr = ssh_client.exec_command(
r'find /var/log -type f \( -name "*.log" -o -name "messages" -o -name "syslog" \) 2>/dev/null | head -20'
)
log_files = stdout.read().decode('utf-8').strip().split('\n')
log_files = [f.strip() for f in log_files if f.strip()]
if log_files:
with print_lock:
print(f"[{ap_name}] Found {len(log_files)} log file(s)")
for remote_path in log_files:
filename = Path(remote_path).name
local_path = ap_dir / filename
if local_path.exists():
continue
with print_lock:
print(f"[{ap_name}] Downloading {filename}...", end="", flush=True)
try:
with SCPClient(ssh_client.get_transport()) as scp:
scp.get(remote_path, str(local_path))
actual_size = local_path.stat().st_size
with print_lock:
print(f" [OK] ({actual_size:,} bytes)")
result['files'].append({
'remote_path': remote_path,
'local_path': str(local_path),
'size': actual_size,
'type': 'log_file'
})
except Exception as e:
with print_lock:
print(f" [FAIL]: {e}")
if result['files']:
result['success'] = True
with print_lock:
print(f"[{ap_name}] [OK] Downloaded {len(result['files'])} file(s) to {ap_dir}")
else:
result['error'] = "No log files collected"
with print_lock:
print(f"[{ap_name}] WARNING: No log files were collected")
except Exception as e:
result['error'] = str(e)
with print_lock:
print(f"[{ap_name}] [FAIL] Error: {e}")
finally:
if ssh_client:
try:
ssh_client.close()
except:
pass
result['elapsed_time'] = time.time() - start_time
completion_timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
result['end_timestamp'] = completion_timestamp
with print_lock:
if result['success']:
print(f"[{ap_name}] [{completion_timestamp}] [OK] Completed in {result['elapsed_time']:.1f}s")
else:
print(f"[{ap_name}] [{completion_timestamp}] [FAIL] Failed after {result['elapsed_time']:.1f}s")
return result
def collect_controller_support_file(output_dir):
"""
Collect support file from UniFi controller.
Args:
output_dir: Directory to save the support file
Returns:
dict: Result with success status, file path, size, timing
"""
result = {
'success': False,
'file_path': None,
'size': 0,
'error': None,
'elapsed_time': 0,
'start_timestamp': None,
'end_timestamp': None
}
start_time = time.time()
start_timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
result['start_timestamp'] = start_timestamp
try:
with print_lock:
print(f"\n[CONTROLLER] [{start_timestamp}] Generating network support file...")
# Trigger support file generation
# UniFi Network 10.x changed the command format
endpoint = f'/api/s/{UNIFI_SITE_ID}/cmd/system'
payload = {
'cmd': 'support',
'userAgent': 'unifi-climgr/1.0',
'language': 'en-US'
}
try:
response = unifi_utils.make_unifi_api_call('POST', endpoint, json=payload)
with print_lock:
print("[CONTROLLER] [OK] Support file generation initiated")
# Debug: show response to understand controller behavior
if response:
print(f"[CONTROLLER] Response: {response}")
except Exception as e:
result['error'] = f"Failed to initiate support file generation: {e}"
with print_lock:
print(f"[CONTROLLER] [FAIL] Failed to initiate generation: {e}")
result['elapsed_time'] = time.time() - start_time
return result
# Get controller version for diagnostics
try:
status_endpoint = f'/api/s/{UNIFI_SITE_ID}/stat/sysinfo'
status = unifi_utils.make_unifi_api_call('GET', status_endpoint)
if isinstance(status, list) and len(status) > 0:
sysinfo = status[0]
version = sysinfo.get('version', 'unknown')
with print_lock:
print(f"[CONTROLLER] Detected UniFi Network version: {version}")
except Exception as e:
with print_lock:
print(f"[CONTROLLER] Could not get version info: {e}")
# Download the support file - try multiple endpoints (controllers have different paths across versions)
# After controller upgrades, generation may be synchronous, so try download immediately
# Modern controllers (v8+) use /dl/support as primary endpoint
download_urls = [
'/dl/support', # Primary endpoint (works with modern controllers)
f'/api/s/{UNIFI_SITE_ID}/dl/support', # Alternative API path
f'/api/s/{UNIFI_SITE_ID}/dl/support.tar.gz', # Explicit filename
'/dl/support.tar.gz', # Legacy with filename
f'/proxy/network/api/s/{UNIFI_SITE_ID}/dl/support', # UniFi OS path (UDM/UDR)
f'/proxy/network/dl/support', # UniFi OS simplified
f'/api/download/support', # Alternative API path
f'/dl/autobackup/support.tar.gz', # Autobackup path (some versions)
]
timestamp = time.strftime('%Y%m%d-%H%M%S')
filename = f"controller_support_{timestamp}.tar.gz"
file_path = output_dir / filename
download_success = False
total_bytes = 0
# Try each endpoint with brief retries in case generation needs a moment
# Modern controllers generate synchronously, so usually works on first try
max_retries = 2
retry_delay = 3 # Wait 3 seconds between retries if needed
for retry in range(max_retries):
if download_success:
break
if retry > 0:
with print_lock:
print(f"[CONTROLLER] Retry {retry}/{max_retries-1} after {retry_delay}s delay...")
time.sleep(retry_delay)
for url in download_urls:
try:
with print_lock:
print(f"[CONTROLLER] Trying download URL: {url}")
sys.stdout.flush()
download_start = time.time()
total_bytes = 0 # Reset for this attempt
response = unifi_utils.make_unifi_api_call('GET', url, stream=True)
chunk_size = 1024 * 1024 # 1MB chunks
with open(file_path, 'wb') as f:
while True:
chunk = response.read(chunk_size)
if not chunk:
break
f.write(chunk)
total_bytes += len(chunk)
response.close()
# Validate downloaded file (support files should be at least 100KB)
if total_bytes < 102400:
raise Exception(f"Downloaded file too small ({total_bytes} bytes), likely not a valid support file")
download_time = time.time() - download_start
speed_mbps = (total_bytes / (1024 * 1024)) / download_time if download_time > 0 else 0
with print_lock:
print(f"[CONTROLLER] [OK] Downloaded support file ({total_bytes} bytes) in {download_time:.1f}s ({speed_mbps:.1f} MB/s)")
sys.stdout.flush()
download_success = True
break
except Exception as e:
error_msg = str(e)
with print_lock:
print(f"[CONTROLLER] Failed: {error_msg}")
sys.stdout.flush()
if file_path.exists():
file_path.unlink()
continue
if not download_success:
attempted_urls = '\n '.join(download_urls)
result['error'] = f"Could not download support file from any known endpoint.\nAttempted URLs:\n {attempted_urls}\n\nYou can manually download the support file from:\nSettings > System > Maintenance > Download Support File"
with print_lock:
print(f"[CONTROLLER] [FAIL] Could not download support file from any endpoint")
print(f"[CONTROLLER] Attempted {len(download_urls)} different endpoints across {max_retries} retries")
print(f"[CONTROLLER] You can manually download from: Settings > System > Maintenance > Download Support File")
result['elapsed_time'] = time.time() - start_time
return result
result['success'] = True
result['file_path'] = str(file_path)
result['size'] = total_bytes
result['elapsed_time'] = time.time() - start_time
size_mb = total_bytes / (1024 * 1024)
with print_lock:
print(f"[CONTROLLER] [OK] Saved to {filename} ({size_mb:.1f} MB)")
sys.stdout.flush()
except Exception as e:
result['error'] = f"Unexpected error: {e}"
with print_lock:
print(f"[CONTROLLER] [FAIL] Error: {e}")
if result['elapsed_time'] == 0:
result['elapsed_time'] = time.time() - start_time
completion_timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
result['end_timestamp'] = completion_timestamp
with print_lock:
if result['success']:
print(f"[CONTROLLER] [{completion_timestamp}] [OK] Completed in {result['elapsed_time']:.1f}s")
else:
print(f"[CONTROLLER] [{completion_timestamp}] [FAIL] Failed after {result['elapsed_time']:.1f}s")
return result
def collect_all_ap_logs(output_dir, aps, ssh_username, ssh_password, parallel=0, timeout=60, include_controller=True):
"""
Collect logs from multiple APs in parallel.
Args:
output_dir: Base output directory
aps: List of AP dictionaries from UniFi API
ssh_username: SSH username
ssh_password: SSH password
parallel: Number of parallel workers (0 = unlimited)
timeout: SSH timeout in seconds
include_controller: Whether to collect controller support file
Returns:
tuple: (ap_results, controller_result, collection_info)
"""
# Create unique collection subdirectory
timestamp = time.strftime('%Y%m%d-%H%M%S')
collection_dir = output_dir / f"collection_{timestamp}"
collection_dir.mkdir(parents=True, exist_ok=True)
print(f"Output directory: {output_dir.absolute()}")
print(f"Collection directory: {collection_dir.name}\n")
collection_start_time = time.time()
collection_start_timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
# Determine worker count
if parallel > 0:
max_workers = parallel + 1 # +1 for controller
else:
max_workers = len(aps) + 1 # All APs + controller
print(f"Using parallel collection with {max_workers} worker(s)\n")
results = []
def collect_with_info(ap_info):
i, total, ap = ap_info
ap_name = ap.get("name", "Unknown")
ap_mac = ap.get("mac", "unknown")
ap_ip = ap.get("ip")
ap_state = unifi_utils.get_ap_state(ap_mac)
with print_lock:
print(f"{'='*60}")
print(f"[{i}/{total}] {ap_name} ({ap_ip}) - {ap_state}")
print(f"{'='*60}\n")
if not ap_ip:
with print_lock:
print(f"WARNING: Skipping {ap_name}: No IP address")
return {
'ap_name': ap_name,
'success': False,
'error': 'No IP address'
}
return collect_logs_from_ap(
ap_ip=ap_ip,
ap_name=ap_name,
ap_mac=ap_mac,
ssh_username=ssh_username,
ssh_password=ssh_password,
output_dir=collection_dir,
timeout=timeout
)
# Execute parallel collection
ap_infos = [(i, len(aps), ap) for i, ap in enumerate(aps, 1)]
with ThreadPoolExecutor(max_workers=max_workers) as executor:
# Submit controller task if requested
controller_future = None
if include_controller:
controller_future = executor.submit(collect_controller_support_file, collection_dir)
# Submit all AP tasks
future_to_ap = {executor.submit(collect_with_info, ap_info): ap_info for ap_info in ap_infos}
# Collect AP results as they complete
for future in as_completed(future_to_ap):
result = future.result()
results.append(result)
# Wait for controller result
controller_result = controller_future.result() if controller_future else None
collection_end_time = time.time()
collection_end_timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
collection_elapsed = collection_end_time - collection_start_time
collection_info = {
'start_timestamp': collection_start_timestamp,
'end_timestamp': collection_end_timestamp,
'elapsed_time': collection_elapsed,
'collection_dir': collection_dir,
'timestamp': timestamp
}
return results, controller_result, collection_info
# ==============================================================================
# HELPER FUNCTIONS
# ==============================================================================
def _strip_default_domain(dns_name: str, default_domain: str = "") -> str:
"""
Strip default domain suffix from DNS name to make it narrower.
E.g., if default_domain is "example.com", "host.example.com" becomes "host"
"""
if not dns_name or dns_name in ["N/A", "No reverse DNS"]:
return dns_name
if default_domain and dns_name.endswith("." + default_domain):
return dns_name[: -(len(default_domain) + 1)]
return dns_name
def _build_client_row(client: dict) -> dict:
"""
Build a display row for a single client.
Consolidates all display value transformations in one place.
Returns a dict with all column values ready for display.
"""
status_text = "Online" if client.get("is_connected_live", False) else "Offline"
signal_display = (
str(client.get('live_signal'))
if client.get('is_connected_live') and client.get('live_signal') is not None
else "N/A"
)
tx_retries_display = (
str(client.get('tx_retries'))
if client.get('is_connected_live') and client.get('tx_retries') is not None
else "N/A"
)
locked_ap_status_display = "Yes" if client.get("is_ap_locked", False) else "No"
# Format uptime for online clients
uptime_display = "N/A"
if client.get("is_connected_live") and client.get("live_uptime") is not None:
uptime_seconds = client.get("live_uptime")
try:
uptime_display = _format_uptime(int(uptime_seconds))
except (TypeError, ValueError):
uptime_display = "N/A"
# Normalize MAC addresses to lowercase
locked_ap_mac_val = client.get("locked_ap_mac", "N/A")
locked_ap_mac_display = locked_ap_mac_val.lower() if locked_ap_mac_val != "N/A" else "N/A"
live_ap_mac_val = client.get("live_ap_mac", "N/A")
live_ap_mac_display = live_ap_mac_val.lower() if live_ap_mac_val != "N/A" else "N/A"
return {
"mac": client.get("mac", "N/A").lower() if client.get("mac") else "N/A",
"hostname": client.get("hostname") or "Unknown Host",
"vendor": client.get("oui", "N/A"),
"description": client.get("description", "N/A"),
"status": status_text,
"ip": client.get("display_ip", "N/A"),
"dns_name": client.get("dns_name", "N/A"),
"uptime": uptime_display,
"connected_ap_name": client.get("connected_ap_name", "N/A"),
"connected_ap_mac": live_ap_mac_display,
"channel": client.get("live_channel", "N/A") if client.get("is_connected_live") else "N/A",
"band": client.get("live_band", "N/A") if client.get("is_connected_live") else "N/A",
"wifi_generation": client.get("live_wifi_generation", "N/A") if client.get("is_connected_live") else "N/A",
"ieee_version": client.get("live_ieee_version", "N/A") if client.get("is_connected_live") else "N/A",
"ssid": client.get("live_ssid", "N/A") if client.get("is_connected_live") else "N/A",
"signal": signal_display,
"retries": tx_retries_display,
"locked": locked_ap_status_display,
"locked_ap_name": client.get("locked_ap_name", "N/A"),
"locked_ap_mac": locked_ap_mac_display,
"last_seen": client.get("last_seen_formatted", "N/A"),
}
def _format_security_display(ssid: dict) -> str:
"""
Convert UniFi security info to human-readable format.
Uses wpa_mode field to determine WPA version, handles WPA2/WPA3 transitions.
"""
# Check for WPA2/WPA3 transition (mutual support)
if ssid.get("wpa3_transition", False):
return "WPA2/WPA3"
# Get WPA mode (wpa, wpa2, wpa3, open, etc.)
wpa_mode = ssid.get("wpa_mode", "").lower()
# Direct mapping of wpa_mode values
wpa_mode_map = {
"wpa": "WPA",
"wpa2": "WPA2",
"wpa3": "WPA3",
"open": "Open",
"": "Open",
}
if wpa_mode in wpa_mode_map:
return wpa_mode_map[wpa_mode]
# Fallback to security field if wpa_mode is not recognized
security_raw = ssid.get("security", "")
if not security_raw:
return "Open"
sec_lower = security_raw.lower()
security_map = {
"open": "Open",
"wpapsk": "WPA",
"wpa2psk": "WPA2",
"wpa3psk": "WPA3",
"wep": "WEP",
}
if sec_lower in security_map:
return security_map[sec_lower]
# Fallback: capitalize if unknown
return security_raw.upper()
def _calculate_mesh_hops(ap: dict, all_devices: list) -> int:
"""
Calculate the number of mesh hops for an AP.
Hops = number of AP-to-AP mesh connections from this AP to a wired AP.
For example:
- Wired AP = 0 hops
- AP connected directly to wired AP = 1 hop
- AP connected to an AP that is connected to wired = 2 hops
- etc.
Returns the hop count, or 0 if unable to determine.
"""
visited = set() # Prevent infinite loops
current_ap = ap
hop_count = 0
while True:
# Check if current AP is wired
is_wired = current_ap.get('wired')
if is_wired is True:
return hop_count
raw_uplink_type = current_ap.get('uplink', {}).get('type')
if raw_uplink_type == 'wire':
return hop_count
# Get the uplink AP MAC
uplink_mac = current_ap.get('uplink_ap_mac') or current_ap.get('last_uplink', {}).get('uplink_mac')
if not uplink_mac or uplink_mac == "N/A":
# No uplink found, return what we have
return hop_count
# Prevent infinite loops
if uplink_mac in visited:
return hop_count
visited.add(uplink_mac)
# Find the uplink AP device
uplink_ap = None
for device in all_devices:
if device.get('mac') == uplink_mac and device.get('type') == 'uap':
uplink_ap = device
break
if not uplink_ap:
# Can't find the uplink AP, return what we have
return hop_count
# Move to uplink AP and increment hop count
current_ap = uplink_ap
hop_count += 1
def _build_ssid_row(ssid: dict) -> dict:
"""
Build a display row for a single SSID.
Returns a dict with all column values ready for display.
Band is determined from wlan_bands field (array of "2g", "5g", "6g").
Falls back to wlan_band if wlan_bands not available.
Security is determined from wpa_mode with fallback to security field.
"""
enabled_display = "Yes" if ssid.get("enabled", False) else "No"
security_display = _format_security_display(ssid)
# Get band from wlan_bands array or wlan_band string
bands = []
wlan_bands = ssid.get("wlan_bands", [])
if wlan_bands:
# wlan_bands is an array like ["5g"] or ["2g", "5g"]
for band in wlan_bands:
if band.lower() == "2g":
bands.append("2.4GHz")
elif band.lower() == "5g":
bands.append("5GHz")
elif band.lower() == "6g":
bands.append("6GHz")
else:
# Fallback to wlan_band single string
wlan_band = ssid.get("wlan_band", "").lower()
if wlan_band == "2g":
bands.append("2.4GHz")
elif wlan_band == "5g":
bands.append("5GHz")
elif wlan_band == "6g":
bands.append("6GHz")
band_display = ", ".join(bands) if bands else "N/A"
return {
"name": ssid.get("name", "N/A"),
"enabled": enabled_display,
"security": security_display,
"band": band_display,
}
def _format_uptime(uptime_seconds: int) -> str:
"""
Format uptime in human-readable format: y m w d h:m:s
Omits zero values until first non-zero, then shows all remaining values.
Examples: "4d 2h:03m:45s", "1y 2m 3d 4h:05m:06s", "45s"
"""
if not uptime_seconds or uptime_seconds <= 0:
return "N/A"
# Calculate time units
total_seconds = uptime_seconds
years = total_seconds // (365 * 86400)
total_seconds %= (365 * 86400)
months = total_seconds // (30 * 86400)
total_seconds %= (30 * 86400)
weeks = total_seconds // (7 * 86400)
total_seconds %= (7 * 86400)
days = total_seconds // 86400
total_seconds %= 86400
hours = total_seconds // 3600
total_seconds %= 3600
minutes = total_seconds // 60
secs = total_seconds % 60
# List of (value, unit) tuples in order from longest to shortest
units = [
(years, "y"),
(months, "m"),
(weeks, "w"),
(days, "d"),
]
# Find first non-zero unit
started = False
parts = []
for value, unit in units:
if value > 0:
started = True
if started:
parts.append(f"{value}{unit}")
# Always show time component (h:m:s) if we've started or there's time left
if started or hours > 0 or minutes > 0 or secs > 0:
time_str = f"{hours}h:{minutes:02d}m:{secs:02d}s"
# If nothing shown yet (only seconds), simplify
if not started and hours == 0 and minutes == 0:
return f"{secs}s"
parts.append(time_str)
return " ".join(parts) if parts else "0s"
def _build_ap_row(ap: dict, all_devices: list) -> dict:
"""
Build a display row for a single AP.
Consolidates all AP display value transformations in one place.
"""
ap_name = ap.get("name") or ap.get("model", "Unknown AP")
mac_address = ap.get("mac", "N/A")
ip_address = ap.get("ip", "N/A")
version = ap.get("version", "N/A")
uptime_seconds = ap.get("uptime", 0)
# Determine connection type (wired vs mesh)
connection_type_display = "N/A"
is_wired_status = ap.get('wired')
if is_wired_status is True:
connection_type_display = "wired"
elif is_wired_status is False:
connection_type_display = "mesh"
else:
raw_uplink_type = ap.get('uplink', {}).get('type')
if raw_uplink_type == 'wire':
connection_type_display = "wired"
elif raw_uplink_type in ['mesh', 'wireless']:
connection_type_display = "mesh"
# For mesh APs, calculate hop count
if connection_type_display == "mesh":
hops = _calculate_mesh_hops(ap, all_devices)
hop_label = "hop" if hops == 1 else "hops"
connection_type_display = f"mesh ({hops}-{hop_label})"
# Determine uplink AP name and MAC for mesh APs
uplink_ap_name_display = "N/A"
uplink_ap_mac_display = "N/A"
if "mesh" in connection_type_display:
uplink_mac = ap.get('uplink_ap_mac') or ap.get('last_uplink', {}).get('uplink_mac')
if uplink_mac and uplink_mac != "N/A":
uplink_ap_mac_display = uplink_mac
# Look up the uplink AP's name
for device in all_devices:
if device.get('mac') == uplink_mac and device.get('type') == 'uap':