-
Notifications
You must be signed in to change notification settings - Fork 9
/
async_run.py
executable file
·1389 lines (1337 loc) · 57.6 KB
/
async_run.py
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
__version__ = "23.06.19.01"
__author__ = "Oren Brigg"
__author_email__ = "[email protected]"
__license__ = "Cisco Sample Code License, Version 1.1 - https://developer.cisco.com/site/license/cisco-sample-code-license/"
import os
import sys
import time
import meraki
import asyncio
import requests
import meraki.aio
from getpass import getpass
from rich import print as pp
from rich.table import Table
from openpyxl import Workbook
from rich.console import Console
from openpyxl.styles import Font, Color
def select_org():
# Fetch and select the organization
print("\n\nFetching organizations...\n")
try:
organizations = dashboard.organizations.getOrganizations()
except Exception as e:
pp(f"[red]An error has occured: \n\n{e}[/red]\n\nExiting...")
pp("A newly generated API key will require up to 15 minutes to synchronize with Meraki API gateways. \
\nIf you're using a new key - kindly try again in a few minutes.")
sys.exit(1)
organizations.sort(key=lambda x: x["name"])
ids = []
table = Table(title="Meraki Organizations")
table.add_column("Organization #", justify="left", style="cyan", no_wrap=True)
table.add_column("Org Name", justify="left", style="cyan", no_wrap=True)
counter = 0
for organization in organizations:
ids.append(organization["id"])
table.add_row(str(counter), organization["name"])
counter += 1
console = Console()
console.print(table)
isOrgDone = False
while isOrgDone == False:
selected = input(
"\nKindly select the organization ID you would like to query: "
)
try:
if int(selected) in range(0, counter):
isOrgDone = True
else:
print("\t[red]Invalid Organization Number\n")
except:
print("\t[red]Invalid Organization Number\n")
return (organizations[int(selected)]["id"], organizations[int(selected)]["name"])
async def async_check_network_health_alerts(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict
):
"""
This fuction checks the network health alerts for a given network.
"""
# print(f"\t\tChecking network health alerts for network: {network['name']}")
try:
alerts = await aiomeraki.networks.getNetworkHealthAlerts(network["id"])
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
if len(alerts) == 0:
pp(f"[green]No network health alerts for network {network['name']}")
results[network["name"]]["network_health_alerts"] = {"is_ok": True}
else:
result = {"is_ok": False, "alert_list": []}
pp(f"[red]Network alerts detected for network {network['name']}")
for alert in alerts:
try:
del alert["scope"]["devices"][0]["url"]
del alert["scope"]["devices"][0]["mac"]
except:
pass
result["alert_list"].append(
{
"severity": alert["severity"],
"category": alert["category"],
"type": alert["type"],
"details": alert["scope"],
}
)
pp(
f"[red]Severity: {alert['severity']}\tCategory: {alert['category']}\tType: {alert['type']}"
)
results[network["name"]]["network_health_alerts"] = result
async def async_check_wifi_channel_utilization(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict
):
"""
This fuction checks the wifi channel utilization for a given network.
if the channel utilization is above the threshold, the check will fail.
it will populate "results" with a dictionary with the result for each AP.
e.g. {
'is_ok': False,
'Q2KD-XXXX-XXXX': {'is_ok': False, 'name': 'AP1', 'utilization': 51.66, 'occurances': 3},
'Q2KD-XXXX-XXXX': {'is_ok': False, 'name': 'AP2', 'utilization': 56.69, 'occurances': 17},
'Q2KD-XXXX-XXXX': {'is_ok': True, 'name': 'AP3', 'utilization': 16.93, 'occurances': 8},
'Q2KD-XXXX-XXXX': {'is_ok': False, 'name': 'AP4', 'utilization': 59.48, 'occurances': 1}
}
"""
# print(f"\t\tChecking wifi channel utilization for network: {network['name']}")
result = {"is_ok": True}
try:
channel_utilization = (
await aiomeraki.networks.getNetworkNetworkHealthChannelUtilization(
network["id"], perPage=100
)
)
# TODO: pagination
for ap in channel_utilization:
utilization_list = [
ap["wifi1"][util]["utilization"] for util in range(len(ap["wifi1"]))
]
exceeded_utilization_list = [
utilization
for utilization in utilization_list
if utilization > thresholds["5G Channel Utilization"]
]
if len(utilization_list) == 0:
pp(f"[yellow]AP {ap['serial']} does not have 5GHz enabled. Skipping...")
elif len(exceeded_utilization_list) > 0:
pp(
f"[red]5GHz Channel Utilization exceeded {thresholds['5G Channel Utilization']}% {len(exceeded_utilization_list)} times, with a peak of {max(utilization_list)}% for AP {ap['serial']}"
)
result[ap["serial"]] = {
"is_ok": False,
"utilization": max(utilization_list),
"occurances": len(exceeded_utilization_list),
}
result["is_ok"] = False
else:
pp(
f"[green]5GHz Channel did not exceed {thresholds['5G Channel Utilization']}% for AP {ap['serial']}, max utilization was {max(utilization_list)}"
)
result[ap["serial"]] = {
"is_ok": True,
"utilization": max(utilization_list),
"occurances": 0,
}
# Adding AP names
try:
network_devices = await aiomeraki.networks.getNetworkDevices(network["id"])
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (Network Name "{network["name"]}": \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
for device in network_devices:
if device["serial"] in result:
result[device["serial"]]["name"] = device.get("name", device["serial"])
#
results[network["name"]]["channel_utilization_check"] = result
#
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
results[network["name"]]["channel_utilization_check"] = {"is_ok": False}
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
results[network["name"]]["channel_utilization_check"] = {"is_ok": False}
async def async_check_wifi_rf_profiles(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict
):
"""
This fuction checks the RF profiles for a given network.
it will populate "results" with a dictionary with the result for each AP.
e.g.
{'is_ok': False,
'RF Profile 1': {
'is_ok': False,
'tests': {
'min_power': {'is_ok': True, 'value': 8},
'min_bitrate': {'is_ok': True, 'value': 54},
'channel_width': {'is_ok': True, 'value': '40'},
'rxsop': {'is_ok': False, 'value': -75}
}},
'RF Profile 2': {
'is_ok': True,
'tests': {
'min_power': {'is_ok': True, 'value': 5},
'min_bitrate': {'is_ok': True, 'value': 54},
'channel_width': {'is_ok': False, 'value': 'auto'},
'rxsop': {'is_ok': True, 'value': None}
}}}
"""
# print(f"\t\tChecking WiFi RF Profiles for network: {network['name']}")
result = {"is_ok": True}
try:
rf_profiles = await aiomeraki.wireless.getNetworkWirelessRfProfiles(
network["id"]
)
except:
pp(f"[red]Could not fetch RF profiles for network {network['name']}")
return {
"is_ok": False,
"ERROR": {
"is_ok": False,
"tests": {
"min_power": {"is_ok": False, "value": ""},
"min_bitrate": {"is_ok": True, "value": ""},
"channel_width": {"is_ok": True, "value": ""},
"rxsop": {"is_ok": False, "value": ""},
},
},
}
for rf_profile in rf_profiles:
result[rf_profile["name"]] = {
"is_ok": True,
"tests": {
"min_power": {"is_ok": True},
"min_bitrate": {"is_ok": True},
"channel_width": {"is_ok": True},
"rxsop": {"is_ok": True},
},
}
# Check min TX power
if rf_profile["fiveGhzSettings"]["minPower"] > thresholds["5G Min TX Power"]:
pp(
f"[red]The min TX power is too high at {rf_profile['fiveGhzSettings']['minPower']}dBm (not including antenna gain) for RF profile {rf_profile['name']}"
)
result[rf_profile["name"]]["tests"]["min_power"] = {
"is_ok": False,
"value": rf_profile["fiveGhzSettings"]["minPower"],
}
result[rf_profile["name"]]["is_ok"] = False
result["is_ok"] = False
else:
pp(
f"[green]The min TX power is {rf_profile['fiveGhzSettings']['minPower']}dBm for RF profile {rf_profile['name']}"
)
result[rf_profile["name"]]["tests"]["min_power"] = {
"is_ok": True,
"value": rf_profile["fiveGhzSettings"]["minPower"],
}
# Check min bitrate
if rf_profile["fiveGhzSettings"]["minBitrate"] < thresholds["5G Min Bitrate"]:
pp(
f"[red]The min bitrate is {rf_profile['fiveGhzSettings']['minBitrate']}Mbps for RF profile {rf_profile['name']}"
)
result[rf_profile["name"]]["tests"]["min_bitrate"] = {
"is_ok": False,
"value": rf_profile["fiveGhzSettings"]["minBitrate"],
}
result[rf_profile["name"]]["is_ok"] = False
result["is_ok"] = False
else:
pp(
f"[green]The min bitrate is {rf_profile['fiveGhzSettings']['minBitrate']}Mbps for RF profile {rf_profile['name']}"
)
result[rf_profile["name"]]["tests"]["min_bitrate"] = {
"is_ok": True,
"value": rf_profile["fiveGhzSettings"]["minBitrate"],
}
# Check channel width
if rf_profile["fiveGhzSettings"]["channelWidth"] == "auto":
pp(
f"[red]The channel width is {rf_profile['fiveGhzSettings']['channelWidth']} for RF profile {rf_profile['name']}"
)
result[rf_profile["name"]]["tests"]["channel_width"] = {
"is_ok": False,
"value": rf_profile["fiveGhzSettings"]["channelWidth"],
}
result[rf_profile["name"]]["is_ok"] = False
result["is_ok"] = False
elif (
int(rf_profile["fiveGhzSettings"]["channelWidth"])
> thresholds["5G Max Channel Width"]
):
pp(
f"[red]The channel width is {rf_profile['fiveGhzSettings']['channelWidth']}MHz for RF profile {rf_profile['name']}"
)
result[rf_profile["name"]]["tests"]["channel_width"] = {
"is_ok": False,
"value": rf_profile["fiveGhzSettings"]["channelWidth"],
}
result[rf_profile["name"]]["is_ok"] = False
result["is_ok"] = False
else:
pp(
f"[green]The channel width is {rf_profile['fiveGhzSettings']['channelWidth']}MHz for RF profile {rf_profile['name']}"
)
result[rf_profile["name"]]["tests"]["channel_width"] = {
"is_ok": True,
"value": rf_profile["fiveGhzSettings"]["channelWidth"],
}
# Check if rx-sop is confiugred
if rf_profile["fiveGhzSettings"]["rxsop"] != None:
pp(f"[red]RX-SOP is configured for RF profile {rf_profile['name']}")
result[rf_profile["name"]]["tests"]["rxsop"] = {
"is_ok": False,
"value": rf_profile["fiveGhzSettings"]["rxsop"],
}
result[rf_profile["name"]]["is_ok"] = False
result["is_ok"] = False
else:
pp(f"[green]RX-SOP is not configured for RF profile {rf_profile['name']}")
result[rf_profile["name"]]["tests"]["rxsop"] = {
"is_ok": True,
"value": rf_profile["fiveGhzSettings"]["rxsop"],
}
results[network["name"]]["rf_profiles_check"] = result
async def async_check_wifi_ssid_amount(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict
):
"""
This fuction checks the amount of SSIDs for a given network.
e.g. {
'is_ok': False,
'amount': 5
}
"""
# print("\n\t\tChecking WiFi SSID Amount...\n")
result = {"is_ok": True}
try:
ssid_list = await aiomeraki.wireless.getNetworkWirelessSsids(network["id"])
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
enabled_ssid_counter = 0
for ssid in ssid_list:
if ssid["enabled"]:
enabled_ssid_counter += 1
result["ssid_amount"] = enabled_ssid_counter
if enabled_ssid_counter <= thresholds["ssid_amount"]:
pp(
f"[green]There are {enabled_ssid_counter} SSIDs enabled for network {network['name']}"
)
else:
pp(
f"[red]There are {enabled_ssid_counter} SSIDs enabled for network {network['name']}"
)
result["is_ok"] = False
results[network["name"]]["ssid_amount_check"] = result
async def async_check_switches_port_counters(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict
):
"""
This fuction checks the port counters for all switches in a given network.
it will return a dictionary with the result for each switch.
e.g. {
'is_ok': False,
'Switch 1': {'is_ok': False, 'crc': ['3'], 'collision': [], 'broadcast': ['17', '18', '19', '20', '27'], 'multicast': [], 'topology_changes': []},
'Switch 2': {'is_ok': False, 'crc': [], 'collision': ['5'], 'broadcast': ['1', '14', '49'], 'multicast': [], 'topology_changes': []},
'Switch 3': {'is_ok': True, 'crc': [], 'collision': [], 'broadcast': [], 'multicast': [], 'topology_changes': []},
}
"""
# print(f"\t\tChecking Switch Port Counters for network {network['name']}...")
try:
device_list = await aiomeraki.networks.getNetworkDevices(network["id"])
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
results[network["name"]]["port_counters_check"] = {"is_ok": True}
port_check_task = []
for device in device_list:
if "MS" in device["model"] or "C9" in device["model"]:
if "name" not in device.keys():
device["name"] = device["serial"]
port_check_task.append(
async_check_switch_port_counters(aiomeraki, network, device)
)
results[network["name"]]["port_counters_check"][device["name"]] = {
"is_ok": True
}
#
for task in asyncio.as_completed(port_check_task):
await task
async def async_check_switch_port_counters(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict, device: dict
):
# print(f"\t\tChecking Switch Port Counters for network {network['name']}...")
result = {
"is_ok": True,
"crc": [],
"collision": [],
"broadcast": [],
"multicast": [],
"topology_changes": [],
}
try:
switch_counters = await aiomeraki.switch.getDeviceSwitchPortsStatusesPackets(
device["serial"]
)
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
for port in switch_counters:
for port_counter in port["packets"]:
# CRC and collision errors
if port_counter["desc"] == "CRC align errors" and port_counter["total"] > 0:
pp(
f"[red]{port_counter['total']} CRC errors on switch {device['name']} - port {port['portId']}"
)
result["crc"].append(port["portId"])
result["is_ok"] = False
if port_counter["desc"] == "Collisions" and port_counter["total"] > 0:
pp(
f"[red]{port_counter['total']} collisions on switch {device['name']} - port {port['portId']}"
)
result["collision"].append(port["portId"])
result["is_ok"] = False
# Broadcast and Multicast rates
if (
port_counter["desc"] == "Broadcast"
and port_counter["ratePerSec"]["total"] > thresholds["broadcast_rate"]
):
pp(
f"[red]{port_counter['ratePerSec']['total']} broadcast/s on switch {device['name']} - port {port['portId']}"
)
result["broadcast"].append(port["portId"])
result["is_ok"] = False
if (
port_counter["desc"] == "Multicast"
and port_counter["ratePerSec"]["total"] > thresholds["multicast_rate"]
):
pp(
f"[red]{port_counter['ratePerSec']['total']} multicast/s on switch {device['name']} - port {port['portId']}"
)
result["multicast"].append(port["portId"])
result["is_ok"] = False
# Topology changes
if (
port_counter["desc"] == "Topology changes"
and port_counter["total"] > thresholds["topology_changes"]
):
pp(
f"[red]{port_counter['total']} topology changes on switch {device['name']} - port {port['portId']}"
)
result["topology_changes"].append(port["portId"])
result["is_ok"] = False
if results[network["name"]]["port_counters_check"][device["name"]]["is_ok"]:
pp(f"[green]No port errors on switch {device['name']}")
results[network["name"]]["port_counters_check"][device["name"]] = result
async def async_check_switch_stp(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict
):
"""
This fuction checks the STP status for a given network.
"""
# print("\n\t\tChecking Switch STP Status...\n")
try:
stp_status = await aiomeraki.switch.getNetworkSwitchStp(network["id"])
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
if stp_status["rstpEnabled"]:
pp(f"[green]STP is enabled for network {network['name']}")
results[network["name"]]["stp_check"] = {"is_ok": True}
else:
pp(f"[red]STP is disabled for network {network['name']}")
results[network["name"]]["stp_check"] = {"is_ok": False}
async def async_check_switch_mtu(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict
):
"""
This fuction checks the MTU of a given network.
"""
# print(f"\t\tChecking Switch MTU for network {network['name']}...")
try:
mtu = await aiomeraki.switch.getNetworkSwitchMtu(network["id"])
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
if mtu["defaultMtuSize"] == 9578 and mtu["overrides"] == []:
pp(
f"[green]Jumbo Frames enabled for network {network['name']} (MTU: {mtu['defaultMtuSize']})"
)
results[network["name"]]["mtu_check"] = {"is_ok": True}
else:
pp(
f"[red]Jumbo Frames disabled for network {network['name']} (MTU: {mtu['defaultMtuSize']}).\
\nIt's recommended to keep at default of 9578 unless intermediate devices don’t support jumbo frames"
)
results[network["name"]]["mtu_check"] = {"is_ok": False}
async def async_check_switch_storm_control(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict
):
"""
This fuction checks the storm control settings of a given network.
"""
# print(f"\t\tChecking Switch Storm Control for network: {network['name']}...")
try:
storm_control = await aiomeraki.switch.getNetworkSwitchStormControl(
network["id"]
)
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
try:
if (
storm_control["broadcastThreshold"] < 100
and storm_control["multicastThreshold"] < 100
and storm_control["unknownUnicastThreshold"] < 100
):
pp(f"[green]Storm-control is enabled for network {network['name']}.")
results[network["name"]]["storm_control"] = {"is_ok": True}
else:
pp(
f"[yellow]Storm-control is disabled for network {network['name']}. Best practices suggest a limit should be configured."
)
results[network["name"]]["storm_control"] = {"is_ok": False}
except:
pp(f"[yellow]Storm-control is not supported for network {network['name']}.")
results[network["name"]]["storm_control"] = {"is_ok": False}
async def async_check_network_firmware(
aiomeraki: meraki.aio.AsyncDashboardAPI, network: dict
):
"""
This fuction checks the firmware versions of a given network.
e.g. {
'appliance': {'current_version_name': 'MX 16.15', 'latest_stable_version': 'MX 16.15'},
'wireless': {'current_version_name': 'MR 27.7.1', 'latest_stable_version': 'MR 28.5'}
}
"""
result = {"is_ok": True}
# print(f"\t\tChecking Firmware Version for network {network['name']}...")
try:
response = await aiomeraki.networks.getNetworkFirmwareUpgrades(network["id"])
firmware = response["products"]
for product in firmware:
current_version = firmware[product]["currentVersion"]["shortName"]
# Looking for the latest stable version
for version in firmware[product]["availableVersions"]:
if version["releaseType"] == "stable":
latest_stable_version = version["shortName"]
if current_version == latest_stable_version:
pp(
f"[green]{network['name']}: {product.upper()} is running the current stable version ({current_version})."
)
elif firmware[product]["nextUpgrade"]["time"] != "":
pp(
f"[green]{network['name']}: {product.upper()} is not running the current stable version ({current_version}), but an upgrade is scheduled for {firmware[product]['nextUpgrade']['time']}"
)
else:
pp(
f"[red]{network['name']}: {product.upper()} is not running the current stable version (current: {current_version}, current stable version: {latest_stable_version})"
)
result["is_ok"] = False
#
result[product] = {
"current_version": current_version,
"latest_stable_version": latest_stable_version,
"scheduled_upgrade": firmware[product]["nextUpgrade"]["time"],
}
results[network["name"]]["network_firmware_check"] = result
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
async def async_check_org_admins(aiomeraki: meraki.aio.AsyncDashboardAPI):
"""
This fuction checks the administration settings of the organization.
it will return a dictionary with the results for the admin checks.
e.g. {
'is_ok': False,
'more_than_one_admin': True,
'users': {
'123456': {'email': '[email protected]', 'name': 'user1', '2fa': True, 'api_calls': 50},
'654321': {'email': '[email protected]', 'name': 'user2', '2fa': False, 'api_calls': 50}},
'missing_2fa': True,
'api_calls': 127
}
"""
# print(f"\t\tAnalyzing organization admins...")
results["org_settings"] = {
"is_ok": False,
"more_than_one_admin": False,
"users": {},
"missing_2fa": True,
"api_calls": 0,
"using_v0": False,
}
try:
org_admins = await aiomeraki.organizations.getOrganizationAdmins(org_id)
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
for admin in org_admins:
results["org_settings"]["users"][admin["id"]] = {
"email": admin["email"],
"name": admin["name"],
"2fa": admin["twoFactorAuthEnabled"],
"api_calls": 0,
"using_v0": False,
}
if admin["twoFactorAuthEnabled"] == False:
pp(
f"[yellow]Missing 2FA for admin {admin['name']} (email: {admin['email']})"
)
else:
pp(
f"[green]Admin {admin['name']} (email: {admin['email']}) has 2FA enabled"
)
# Filter full right admins (not just read-only or network specific admins)
full_right_admins = [admin for admin in org_admins if admin["orgAccess"] == "full"]
if len(full_right_admins) > 1:
results["org_settings"]["more_than_one_admin"] = True
pp(f"[green]More than one admin has full rights. This is recommended.")
else:
pp(
f"[red]Only one admin has full rights. It's recommended to have at least one admin with full rights."
)
if (
results["org_settings"]["more_than_one_admin"] == True
and results["org_settings"]["missing_2fa"] == []
):
results["org_settings"]["is_ok"] = True
else:
results["org_settings"]["is_ok"] = False
# Check API access
check_api_calls_tasks = [
async_check_api_calls(aiomeraki, admin["id"]) for admin in org_admins
]
for task in asyncio.as_completed(check_api_calls_tasks):
await task
api_call_count = 0
for admin in results["org_settings"]["users"]:
api_call_count += results["org_settings"]["users"][admin]["api_calls"]
results["org_settings"]["api_calls"] = api_call_count
pp(
f"API access usage: {results['org_settings']['api_calls']} API calls during the last week."
)
async def async_check_api_calls(
aiomeraki: meraki.aio.AsyncDashboardAPI, org_admin: str
):
try:
api_requests = await aiomeraki.organizations.getOrganizationApiRequests(
org_id, adminId=org_admin, timespan=7 * 86400, perPage=1000, total_pages=10
)
except meraki.exceptions.AsyncAPIError as e:
pp(
f'[bold magenta]Meraki AIO API Error (OrgID "{ org_id }", OrgName "{ org_name }"): \n { e }'
)
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
for request in api_requests:
results["org_settings"]["users"][request["adminId"]]["api_calls"] += 1
if "/v0/" in request["path"]:
results["org_settings"]["using_v0"] = True
if not results["org_settings"]["users"][request["adminId"]]["using_v0"]:
pp(
f"[red]Admin {results['org_settings']['users'][request['adminId']]['name']} (email: {results['org_settings']['users'][request['adminId']]['email']}) is using the v0 API"
)
results["org_settings"]["users"][request["adminId"]]["using_v0"] = True
results["org_settings"]["is_ok"] = False
def check_wireless_ports(networks: list):
# Fetch all APs' ethernet port statuses
aggregated_ap_uplinks = []
startingAfter = ''
isDone = False
while not isDone:
pp(f"Fetching ethernet ports, received {len(aggregated_ap_uplinks)} ethernet ports so far..")
try:
ap_uplinks = dashboard.wireless.getOrganizationWirelessDevicesEthernetStatuses(org_id, perPage=1000, startingAfter=startingAfter)
aggregated_ap_uplinks += ap_uplinks
if len(ap_uplinks) < 1000:
isDone = True
else:
startingAfter = ap_uplinks[999]['serial']
except Exception as e:
pp(f"[bold magenta]Some other ERROR: {e}")
isDone = True
#
for ap in aggregated_ap_uplinks:
# Translating network ID to network name
network_id = ap['network']['id']
network_name = "N/A"
for network in networks:
if network['id'] == network_id:
network_name = network['name']
break
# Checking if the AP has 5GHz history, otherwise it won't appear in the results
if ap["serial"] in results[network_name]["channel_utilization_check"].keys():
# Checking the APs uplink
# TODO: Adjust the code for APs with more than one port
ap_port = ap['ports'][0]
results[network_name]["channel_utilization_check"][ap["serial"]]["speed"] = ap_port['linkNegotiation']['speed']
results[network_name]["channel_utilization_check"][ap["serial"]]["duplex"] = ap_port['linkNegotiation']['duplex']
results[network_name]["channel_utilization_check"][ap["serial"]]["power"] = ap['power']['mode']
#
if ap_port['linkNegotiation']['speed'] == None or ap_port['linkNegotiation']['speed'] < 1000:
results[network_name]["channel_utilization_check"][ap["serial"]]["is_ok"] = False
if ap_port['linkNegotiation']['duplex'] == 'half' or ap_port['linkNegotiation']['duplex'] == None:
results[network_name]["channel_utilization_check"][ap["serial"]]["is_ok"] = False
if ap['power']['mode'] != 'full':
results[network_name]["channel_utilization_check"][ap["serial"]]["is_ok"] = False
def generate_excel_report(results: dict) -> None:
print("\n\t\tGenerating an Excel Report...\n")
ABC = [None, "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
workbook = Workbook()
sheet = workbook.active
#
# Intro tab
sheet.title = "Introduction"
sheet["B3"] = "Introduction to the Meraki health check report"
sheet[
"B5"
] = "Cisco Meraki is an amazing cloud-managed IT solution, simplifying network, security, security cameras, and IoT infrastructure."
sheet[
"B6"
] = "However, even the most intelligent AI/ML-driven solution is still vulnerable to users misconfiguring various options (usually without reading the documentation)."
sheet[
"B7"
] = "Misconfiguration can result in an outage, or poor user experience (if you will limit user's traffic to 1Mbps - things will work slowly.. AI won't help there as it's the admin's 'intent')."
sheet[
"B9"
] = "This report is presenting the alignment between your Meraki networks' state and configuration with Meraki best practices, "
sheet[
"B10"
] = "and a set of thresholds I have selected based on my personal experience."
sheet["B12"] = "In the report you will find the following tabs:"
sheet[
"B13"
] = "1. Summary - This tab presents a summary of the results of the health check."
sheet[
"B14"
] = "2. Network Health Alerts - This tab presents the dashboard alerts from all networks in a single view."
sheet[
"B15"
] = f"3. Network Health - This tab presents the Channel Utilization for every wireless AP. We will examine only the 5GHz spectrum; If you are using the 2.4GHz spectrum - it's beyond saving..."
sheet[
"C16"
] = f"The threshold is set to {thresholds['5G Channel Utilization']}%. APs with utilization above this threshold for many occurrences (10+) may be experiencing RF issues."
sheet[
"B17"
] = "4. Firmware Upgrade - This tab presents the firmware status for every network. Highlighting networks that require a firmware upgrade."
sheet[
"B18"
] = "5. RF profiles - This tab presents the RF profiles for every network."
sheet[
"C19"
] = f"Minimum Tx power: Setting the minimum Tx power too high, might result in wireless APs interfering with each other, as they are not allowed to decrease their power. The threshold is set to {thresholds['5G Min TX Power']} dBm."
sheet[
"C20"
] = f"Minimum bitrate: Broadcasts and Multicasts will be sent over the wireless at this speed. The lower the speed - the more airtime is wasted. The threshold is set to {thresholds['5G Min Bitrate']} Mbps."
sheet[
"C21"
] = f"Channel Width: Depending on local regulation and wireless AP density, there is a limited number of channels that can be used. In most deployments, channel width of more than {thresholds['5G Max Channel Width']}MHz might cause interference between the wireless APs."
sheet[
"C22"
] = f"RX-SOP: This is a fine-tuning network design tool that should be used only after consulting an independent wireless expert or Meraki Support. If it's configured - there should be a good reason for it. More details at: https://documentation.meraki.com/MR/Radio_Settings/Receive_Start_of_Packet_(RX-SOP)"
sheet[
"B23"
] = f"6. Switch port counters: This tab presents every switch in every network."
sheet[
"C24"
] = f"Ports with CRC errors: We do not expect to see any CRC errors on our network, ports with more than 0 CRC errors will appear here."
sheet[
"C25"
] = f"Ports with collisions: It's 2022.. we shouldn't be seeing hubs or collisions on our network. Ports with more than 0 collisions will appear here."
sheet[
"C26"
] = f"Multicasts exceeding threshold: Multicast traffic may be legitimate, we're highlighting ports with more than {thresholds['multicast_rate']} multicasts per second for visibility (and making sure they are legitimate)."
sheet[
"C27"
] = f"Broadcasts exceeding threshold: Broadcasts above a certain threshold should be looked at, we're highlighting ports with more than {thresholds['broadcast_rate']} broadcasts per second for visibility (and making sure they are legitimate)."
sheet[
"C28"
] = f"Topology changes exceeding threshold: TCN means something has changed in the STP topology. We're highlighting ports with more than {thresholds['topology_changes']} topology changes for visibility (and making sure they are legitimate)."
sheet[
"B29"
] = f"7. Organization Settings - This tab presents the organization settings."
sheet[
"C30"
] = f"Multiple admins: We're looking for a single admin with full rights. If you see more than one admin with full rights - it's recommended to have at least one admin with full rights."
sheet[
"C31"
] = f"2FA: Two Factor Authentication is an important security mechanism, highly recommended for securing your admin accounts."
sheet[
"C32"
] = f"API access: presenting which admin users are using the Dashboard API and whether they are using the v0 API which is being deprecated."
#
# Summary tab
workbook.create_sheet("Summary")
sheet = workbook["Summary"]
sheet["A1"] = "Organization Name"
sheet["B1"] = "Network Name"
sheet["C1"] = "Test Name"
sheet["D1"] = "Test Result"
#
sheet["A2"] = org_name
sheet["B2"] = "N/A"
sheet["C2"] = "Organization Settings"
if results["org_settings"]["is_ok"] == True:
sheet["D2"] = "OK"
else:
sheet["D2"] = "Fail"
sheet["D2"].font = Font(bold=True, color="00FF0000")
#
line = 3
for network in results:
if network == "org_settings":
continue
for test_name in results[network]:
sheet[f"A{line}"] = org_name
sheet[f"B{line}"] = network
sheet[f"C{line}"] = test_name
if results[network][test_name]["is_ok"]:
sheet[f"D{line}"] = "Pass"
else:
sheet[f"D{line}"] = "Fail"
sheet[f"D{line}"].font = Font(bold=True, color="00FF0000")
line += 1
#
# Adding filters
sheet.auto_filter.ref = f"A1:{ABC[sheet.max_column]}{line}"
sheet.auto_filter.add_filter_column(0, ["Test Result"])
#
# Organization Admin tab
workbook.create_sheet("Organization Admin")
sheet = workbook["Organization Admin"]
sheet["A1"] = "Organization Name"
sheet["A2"] = org_name
sheet["B1"] = "2+ admins"
if results["org_settings"]["more_than_one_admin"]:
sheet["B2"] = "Yes"
else:
sheet["B2"] = "No"
sheet["B2"].font = Font(bold=True, color="00FF0000")
sheet["C1"] = "Admins missing 2FA"
sheet["C2"] = (
str(results["org_settings"]["missing_2fa"])
if results["org_settings"]["missing_2fa"] != []
else ""
)
sheet["C2"].font = Font(bold=True, color="00FF0000")
sheet["D1"] = "API Calls (last 7 days)"
sheet["D2"] = results["org_settings"]["api_calls"]
sheet["E1"] = "Using API v0 ?"
if results["org_settings"]["using_v0"]:
sheet["E2"] = "Yes"
sheet["E2"].font = Font(bold=True, color="00FF0000")
else:
sheet["E2"] = "No"
#
sheet["A5"] = "Organization Name"
sheet["B5"] = "Admin Name"
sheet["C5"] = "Admin Email"
sheet["D5"] = "2FA enablement"
sheet["E5"] = "API Calls (last 7 days)"
sheet["F5"] = "Using API v0"
line = 6
for admin in results["org_settings"]["users"]:
sheet[f"A{line}"] = org_name
sheet[f"B{line}"] = results["org_settings"]["users"][admin]["name"]
sheet[f"C{line}"] = results["org_settings"]["users"][admin]["email"]
if results["org_settings"]["users"][admin]["2fa"]:
sheet[f"D{line}"] = "Yes"
else:
sheet[f"D{line}"] = "No"
sheet[f"D{line}"].font = Font(bold=True, color="00FF0000")
sheet[f"E{line}"] = results["org_settings"]["users"][admin]["api_calls"]
if results["org_settings"]["users"][admin]["using_v0"]:
sheet[f"F{line}"] = "Yes"
sheet[f"F{line}"].font = Font(bold=True, color="00FF0000")
else:
sheet[f"F{line}"] = "No"
line += 1
#
# Adding filters
sheet.auto_filter.ref = f"A5:{ABC[sheet.max_column]}{line}"
sheet.auto_filter.add_filter_column(0, ["Admin Name"])
#
# Network Health Alerts tab
workbook.create_sheet("Network Health Alerts")
sheet = workbook["Network Health Alerts"]
sheet["A1"] = "Organization Name"
sheet["B1"] = "Network Name"
sheet["C1"] = "Severity"
sheet["D1"] = "Category"
sheet["E1"] = "Type"
sheet["F1"] = "Details"
line = 2
#
for network in results:
if network == "org_settings":
continue
if results[network]["network_health_alerts"]["is_ok"] == True:
pass
else:
for alert in results[network]["network_health_alerts"]["alert_list"]:
sheet[f"A{line}"] = org_name
sheet[f"B{line}"] = network
sheet[f"C{line}"] = alert["severity"]
sheet[f"D{line}"] = alert["category"]
sheet[f"E{line}"] = alert["type"]
sheet[f"F{line}"] = str(alert["details"])
if alert["severity"] == "critical":
for cell in sheet[line:line]:
cell.font = Font(bold=True, color="00FF0000")
elif alert["severity"] == "warning":
for cell in sheet[line:line]:
cell.font = Font(bold=True, color="00FF9900")
line += 1
#
# Adding filters
sheet.auto_filter.ref = f"A1:{ABC[sheet.max_column]}{line}"
sheet.auto_filter.add_filter_column(0, ["Network Name"])
#
# Network Firmware tab
workbook.create_sheet("Network Firmware")
sheet = workbook["Network Firmware"]
sheet["A1"] = "Organization Name"
sheet["B1"] = "Network Name"
sheet["C1"] = "Product Catagory"
sheet["D1"] = "Current Version"
sheet["E1"] = "Latest Stable Version"
sheet["F1"] = "Scheduled Update"
line = 2
#
for network in results:
if "network_firmware_check" in results[network].keys():
for product in results[network]["network_firmware_check"]:
if product == "is_ok": # skipping the is_ok key
continue
sheet[f"A{line}"] = org_name
sheet[f"B{line}"] = network
sheet[f"C{line}"] = product
sheet[f"D{line}"] = results[network]["network_firmware_check"][product][
"current_version"
]
sheet[f"E{line}"] = results[network]["network_firmware_check"][product][
"latest_stable_version"
]
sheet[f"F{line}"] = results[network]["network_firmware_check"][product][
"scheduled_upgrade"