-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrestoreFunctions.py
2273 lines (2187 loc) · 111 KB
/
restoreFunctions.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
import json
import os
import time
import base64
import sys
import meraki
def merakiRestore(dir, org, nets, dashboard, logger):
"""
Wrapper function for restore operations. Will iterate across the list of networks and perform applicable
restore operations, and return a list of dictionaries of operations with their status.
:param dir: path to backup
:param networks: list of networks being backed up
:param dashboard: Meraki API client
:return: operations: list of operations performed with their status
"""
operations = []
path = dir
if 'organization' in next(os.walk(f"{path}"))[1]:
if 'policy_objects' in next(os.walk(f"{path}/organization"))[1]:
if ('policy_objects.json' and 'policy_objects_groups.json') in next(os.walk(f"{path}/organization/policy_objects"))[2]:
logger.info("Restoring Organization Policy Objects...")
operations.append(restoreOrganizationPolicyObjects(org=org, dashboard=dashboard, path=path, logger=logger))
if 'ipsec_vpn' in next(os.walk(f"{path}/organization"))[1]:
if ('ipsec_vpn.json') in next(os.walk(f"{path}/organization/ipsec_vpn"))[2]:
logger.info("Restoring Organization IPsec VPN...")
operations.append(restoreOrganizationMxIpsecVpn(org=org, dashboard=dashboard, path=path, logger=logger))
if 'vpn_firewall' in next(os.walk(f"{path}/organization"))[1]:
if ('vpn_firewall.json') in next(os.walk(f"{path}/organization/vpn_firewall"))[2]:
logger.info("Restoring Organization VPN Firewall...")
operations.append(restoreOrganizationMxVpnFirewall(org=org, dashboard=dashboard, path=path, logger=logger))
for net in nets:
logger.info(f"Restoring settings for network {net['name']}...")
settings_in_backup = next(os.walk(f"{path}/network/{net['name']}"))[1]
# Check if firmware in backup matches firmware in target network
if 'firmware' in settings_in_backup:
checkFirmware(net=net, dashboard=dashboard, path=path, logger=logger)
devices_in_network = dashboard.networks.getNetworkDevices(networkId=net['id'])
# Restore Network Settings
if 'webhooks' in settings_in_backup:
if ('webhooks_payload_templates.json' and 'webhooks_servers.json') in next(os.walk(f"{path}/network/{net['name']}/webhooks"))[2]:
logger.info("Restoring Webhooks...")
operations.append(restoreNetworkWebhooks(net=net, dashboard=dashboard, path=path, logger=logger))
if 'syslog' in settings_in_backup:
if ('syslog.json') in next(os.walk(f"{path}/network/{net['name']}/syslog"))[2]:
logger.info("Restoring Syslog...")
operations.append(restoreNetworkSyslog(net=net, dashboard=dashboard, path=path, logger=logger))
if 'snmp' in settings_in_backup:
if ('snmp.json') in next(os.walk(f"{path}/network/{net['name']}/snmp"))[2]:
logger.info("Restoring SNMP...")
operations.append(restoreNetworkSnmp(net=net, dashboard=dashboard, path=path, logger=logger))
if 'alert_settings' in settings_in_backup:
if ('alerts.json') in next(os.walk(f"{path}/network/{net['name']}/alert_settings"))[2]:
logger.info("Restoring Alerts...")
operations.append(restoreNetworkAlerts(net=net, dashboard=dashboard, path=path, logger=logger))
if 'floorplans' in settings_in_backup:
if ('floorplans.json') in next(os.walk(f"{path}/network/{net['name']}/floorplans"))[2]:
logger.info("Restoring Floorplans...")
fp_operation, ffp = restoreNetworkFloorplans(net=net, dashboard=dashboard, path=path, logger=logger)
operations.append(fp_operation)
if 'devices' in settings_in_backup:
if ('network_devices.json') in next(os.walk(f"{path}/network/{net['name']}/devices"))[2]:
logger.info("Restoring Network Device settings...")
operation, devices_to_update = restoreNetworkDevices(net=net, org=org, devices_in_network=devices_in_network, dashboard=dashboard, path=path, updated_floorplans=ffp, logger=logger)
operations.append(operation)
if 'appliance' or 'switch' or 'wireless' in net['productTypes'] and 'group_policies' in settings_in_backup:
logger.info("Restoring Group Policies...")
operations.append(restoreNetworkGroupPolicies(net=net, dashboard=dashboard, path=path, logger=logger))
if 'appliance' in net['productTypes'] and 'appliance' in settings_in_backup:
if 'settings' in next(os.walk(f"{path}/network/{net['name']}/appliance"))[1]:
# Restore MX Settings
if 'settings.json' in next(os.walk(f"{path}/network/{net['name']}/appliance/settings"))[2]:
logger.info("Restoring MX appliance settings...")
settings_operation, settings_data = restoreMxSettings(net=net, dashboard=dashboard, path=path, logger=logger)
operations.append(settings_operation)
if settings_data['deploymentMode']=="routed":
if 'vlans' in next(os.walk(f"{path}/network/{net['name']}/appliance"))[1]:
# Restore VLAN config from vlan_config, vlan_ports and vlan_settings files
# Read if VLANs are enabled in the backup
if 'vlan_settings.json' in next(os.walk(f"{path}/network/{net['name']}/appliance/vlans"))[2]:
# Apply VLAN settings
logger.info("Restoring VLAN settings...")
vlan_settings_operation, vlan_settings_data = restoreMxVlanSettings(net=net, dashboard=dashboard, path=path, logger=logger)
operations.append(vlan_settings_operation)
# If VLANs were enabled in the checkpoint, then proceed to configure them individually
if vlan_settings_data['vlansEnabled'] == True and ('vlan_config.json' and 'vlan_ports.json') in next(os.walk(f"{path}/network/{net['name']}/appliance/vlans"))[2]:
logger.info("Restoring MX per VLAN configuration...")
operations.append(restoreMxVlansBatch(org=org, net=net, dashboard=dashboard, path=path, logger=logger))
if 'appliance_routing' in next(os.walk(f"{path}/network/{net['name']}/appliance"))[1]:
# Restore MX Static Routing
# Needs to be restored before it is used for Site to Site VPN configs
if 'static_routes.json' in next(os.walk(f"{path}/network/{net['name']}/appliance/appliance_routing"))[2]:
logger.info('Restoring MX Static Routes...')
operations.append(restoreMxStaticRouting(net=net, dashboard=dashboard, path=path, logger=logger))
elif settings_data['deploymentMode']=='passthrough':
if 'bgp_settings' in next(os.walk(f"{path}/network/{net['name']}/appliance"))[1]:
# Restore MX BGP
if 'bgp.json' in next(os.walk(f"{path}/network/{net['name']}/appliance"))[2]:
logger.info('Restoring MX BGP settings...')
operations.append(restoreMxBgp(net=net, dashboard=dashboard, path=path, logger=logger))
if 'security' in next(os.walk(f"{path}/network/{net['name']}/appliance"))[1]:
# Restore MX Security Settings
if ('amp.json' and 'ips.json') in next(os.walk(f"{path}/network/{net['name']}/appliance/security"))[
2]:
logger.info("Restoring MX Security...")
operations.append(restoreMxSecurity(net=net, dashboard=dashboard, path=path, logger=logger))
# Restore MX Firewall Settings
if ('l3_fw.json' and 'l7_fw.json') in next(os.walk(f"{path}/network/{net['name']}/appliance/security"))[
2]:
logger.info("Restoring MX Firewall...")
operations.append(restoreMxFirewall(net=net, dashboard=dashboard, path=path, logger=logger))
# Restore MX Content Filtering
if ('content_filtering.json') in \
next(os.walk(f"{path}/network/{net['name']}/appliance/security"))[
2]:
logger.info("Restoring MX Content Filtering...")
operations.append(restoreMxContentFiltering(net=net, dashboard=dashboard, path=path, logger=logger))
if 'shaping' in next(os.walk(f"{path}/network/{net['name']}/appliance"))[1]:
# Restore Shaping Settings
if ('global_shaping.json' and 'shaping_rules') in \
next(os.walk(f"{path}/network/{net['name']}/appliance/shaping"))[
2]:
logger.info("Restoring MX Shaping...")
operations.append(restoreMxShaping(net=net, dashboard=dashboard, path=path, logger=logger))
if 'vpn_config' in next(os.walk(f"{path}/network/{net['name']}/appliance"))[1]:
# Restore VPN Settings
if ('vpn_config.json') in \
next(os.walk(f"{path}/network/{net['name']}/appliance/vpn_config"))[
2]:
logger.info("Restoring VPN Settings...")
operations.append(restoreMxVpnConfig(net=net, dashboard=dashboard, path=path, logger=logger))
if 'sdwan_settings' in next(os.walk(f"{path}/network/{net['name']}/appliance"))[1]:
# Restore SDWAN Settings
logger.info("Restoring SDWAN Settings...")
operations.append(restoreMxSdWanSettings(net=net, dashboard=dashboard, path=path, logger=logger))
if 'switch' in net['productTypes']and 'switch' in settings_in_backup:
if 'switch_settings' in next(os.walk(f"{path}/network/{net['name']}/switch"))[1]:
if 'port_schedules.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
logger.info("Restoring Switch Port Schedules...")
operations.append(restoreSwitchPortSchedules(net=net, dashboard=dashboard, path=path, logger=logger))
if 'qos_rules.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
logger.info("Restoring Switch QoS...")
operations.append(restoreSwitchQos(net=net, dashboard=dashboard, path=path, logger=logger))
if 'access_policies.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
logger.info("Restoring Access Policies...")
operations.append(restoreSwitchAccessPolicies(net=net, dashboard=dashboard, path=path, logger=logger))
if len(next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[1])>0:
number_of_switches = len(next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[1])
if number_of_switches > 0:
logger.info(f"Restoring switch ports for {number_of_switches} switches...")
# Restore Switch Ports
operations.append(restoreSwitchPortConfigsBatch(org=org, net=net, dashboard=dashboard,
path=path,
devices_in_network=devices_in_network, logger=logger))
if 'dhcp_policies.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
# Restore Switch DHCP Security
logger.info("Restoring Switch DHCP Policies...")
operations.append(restoreSwitchDhcpSecurity(net=net, dashboard=dashboard, path=path, logger=logger))
if 'switch_stp.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
# Restore Switch STP
logger.info("Restoring Switch STP...")
operations.append(restoreSwitchStp(net=net, dashboard=dashboard, path=path, logger=logger))
if 'switch_acl.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
# Restore Switch ACL
logger.info("Restoring Switch ACL...")
operations.append(restoreSwitchAcl(net=net, dashboard=dashboard, path=path, logger=logger))
if 'switch_dscp_cos.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
# Restore Switch DHCP COS
logger.info("Restoring Switch DHCP COS Mappings...")
operations.append(restoreSwitchDscpCosMap(net=net, dashboard=dashboard, path=path, logger=logger))
if 'switch_storm_control.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
# Restore Switch Storm Control
logger.info("Restoring Switch Storm Control...")
operations.append(restoreSwitchStormControl(net=net, dashboard=dashboard, path=path, logger=logger))
if 'switch_mtu.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
# Restore Switch MTU
logger.info("Restoring Switch MTU...")
operations.append(restoreSwitchMtu(net=net, dashboard=dashboard, path=path, logger=logger))
if 'switch_link_aggregations.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
# Restore Switch Link Aggregation
logger.info("Restoring Switch Link Aggregation...")
operations.append(restoreSwitchLinkAgg(net=net, dashboard=dashboard, path=path, devices_in_network=devices_in_network, logger=logger))
if 'switch_settings.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_settings"))[2]:
# Restore Switch Network Settings
logger.info("Restoring Switch Network Settings...")
operations.append(restoreSwitchSettings(net=net, dashboard=dashboard, path=path, logger=logger))
if 'switch_routing' in next(os.walk(f"{path}/network/{net['name']}/switch"))[1]:
if 'ospf.json' in next(os.walk(f"{path}/network/{net['name']}/switch/switch_routing/"))[2]:
# Restore Switch OSPF
logger.info(f"Restoring Switch OSPF for switch...")
operations.append(restoreSwitchOspf(net=net, dashboard=dashboard, path=path, logger=logger))
if len(next(os.walk(f"{path}/network/{net['name']}/switch/switch_routing"))[1])>0:
# Restore Switch SVIs
logger.info(f"Restoring Switch SVIs...")
operations.append(restoreSwitchSvis(net=net, dashboard=dashboard, path=path, devices_in_network=devices_in_network, logger=logger))
# Restore Switch Static Routes
logger.info(f"Restoring Switch Static Routes...")
operations.append(restoreSwitchStaticRouting(net=net, dashboard=dashboard, path=path, devices_in_network=devices_in_network, logger=logger))
if 'wireless' in net['productTypes']:
if 'ssid_settings' in next(os.walk(f"{path}/network/{net['name']}/wireless"))[1]:
if 'ssids.json' in next(os.walk(f"{path}/network/{net['name']}/wireless/ssid_settings/"))[2]:
# Restore SSID Settings
logger.info("Restoring SSID settings...")
operations.append(restoreMrSsidConfigs(net=net, dashboard=dashboard, path=path, logger=logger))
if 'l3_rules.json' and 'l7_rules.json' in next(os.walk(f"{path}/network/{net['name']}/wireless/ssid_settings/"))[2]:
# Restore SSID FW settings
logger.info("Restoring SSID FW...")
operations.append(restoreMrSsidFW(net=net, dashboard=dashboard, path=path, logger=logger))
if 'shaping_rules.json' in next(os.walk(f"{path}/network/{net['name']}/wireless/ssid_settings/"))[2]:
# Restore SSID Shaping settings
logger.info("Restoring SSID Shaping...")
operations.append(restoreMrSsidShaping(net=net, dashboard=dashboard, path=path, logger=logger))
if 'radio_settings' in next(os.walk(f"{path}/network/{net['name']}/wireless"))[1]:
if 'rf_profiles.json' in next(os.walk(f"{path}/network/{net['name']}/wireless/radio_settings/"))[2]:
# Restore RF Profile settings
logger.info("Restoring RF Profiles...")
operations.append(restoreMrRfProfiles(net=net, dashboard=dashboard, path=path, devices_in_network=devices_in_network, logger=logger))
if 'bluetooth_settings' in next(os.walk(f"{path}/network/{net['name']}/wireless"))[1]:
if 'network_bluetooth_settings.json' in next(os.walk(f"{path}/network/{net['name']}/wireless/bluetooth_settings/"))[2]:
# Restore Bluetooth settings
logger.info("Restoring MR Bluetooth...")
operations.append(restoreMrBluetooth(net=net, dashboard=dashboard, path=path, devices_in_network=devices_in_network, logger=logger))
if 'network_wireless_settings' in next(os.walk(f"{path}/network/{net['name']}/wireless"))[1]:
if 'network_wireless_settings.json' in next(os.walk(f"{path}/network/{net['name']}/wireless/network_wireless_settings/"))[2]:
# Restore Wireless Settings
logger.info("Restoring Wireless Network Settings...")
operations.append(restoreMrWirelessSettings(net=net, dashboard=dashboard, path=path, logger=logger))
return operations
def restoreMxSettings(net, dashboard, path, logger):
"""
Restore MX Settings
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "appliance", "operation": "restoreMxSettings",
"restorePayload": "", "status": ""}
try:
with open(f'{path}/network/{net["name"]}/appliance/settings/settings.json') as fp:
data = json.load(fp)
fp.close()
operation['restorePayload']=data
# Apply VLAN settings
dashboard.appliance.updateNetworkApplianceSettings(networkId=net['id'], **data)
operation['status']="Complete"
except meraki.APIError as e:
logger.error(e)
data =""
operation['status']=e
except Exception as e:
logger.error(e)
data=""
operation["status"]=e
return operation, data
def restoreMxVlanSettings(net, dashboard, path, logger):
"""
Restore MX VLAN Settings
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "appliance", "operation": "restoreMxVlanSettings",
"restorePayload": "", "status": ""}
try:
with open(f'{path}/network/{net["name"]}/appliance/vlans/vlan_settings.json') as fp:
data = json.load(fp)
fp.close()
operation['restorePayload']=data
# Apply VLAN settings
dashboard.appliance.updateNetworkApplianceVlansSettings(networkId=net['id'], **data)
operation['status']="Complete"
except meraki.APIError as e:
logger.error(e)
data =""
operation['status']=e
except Exception as e:
logger.error(e)
data=""
operation["status"]=e
return operation, data
def checkFirmware(net, dashboard, path, logger):
"""
Function to check if the backup firmware versions match the current firmware versions. Discrepancies in firmware versions
can cause incompatibilities and make the script fail. Take this into account when restoring and try to back up often.
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
with open(f'{path}/network/{net["name"]}/firmware/firmware.json') as fp:
backup_firmware = json.load(fp)
fp.close()
current_firmware = dashboard.networks.getNetworkFirmwareUpgrades(net['id'])
prods_in_backup = {product:backup_firmware['products'][product]['currentVersion']['firmware'] for product in backup_firmware['products'].keys()}
prods_in_current = {product:current_firmware['products'][product]['currentVersion']['firmware'] for product in current_firmware['products'].keys()}
for key_b in prods_in_backup.keys():
for key_c in prods_in_current.keys():
if key_b == key_c:
if prods_in_backup[key_b]!=prods_in_current[key_c]:
print(f"Firmware version for {key_b} in backup is {prods_in_backup[key_b]} and {prods_in_current[key_c]} in your existing network. Firmware differences can lead to feature incompatibilities and the restore operation failing.")
proceed = input("Do you wish to proceed? (Y/N): ")
if proceed=='Y':
continue
else:
print("Aborted by user.")
sys.exit()
def restoreNetworkGroupPolicies(net, dashboard, path, logger):
"""
Function to restore a network's group policies.
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "network", "operation": "restoreNetworkGroupPolicies", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/group_policies/group_policies.json') as fp:
group_policies = json.load(fp)
fp.close()
operation['restorePayload']=group_policies
existing_gps = dashboard.networks.getNetworkGroupPolicies(networkId=net['id'])
for policy in group_policies:
# CHECK IF POLICIES EXIST ALREADY BEFORE CREATING
# IF THEY EXIST, JUST UPDATE
update_flag = False
for gp in existing_gps:
if policy['name'] == gp['name']:
update_flag = True
break
if update_flag == True:
group_policy_id = policy['groupPolicyId']
upd = {k: policy[k] for k in policy.keys() - {'groupPolicyId'}}
dashboard.networks.updateNetworkGroupPolicy(networkId=net['id'], groupPolicyId=group_policy_id, **upd)
else:
name = policy['name']
upd = {k: policy[k] for k in policy.keys() - {'name', 'groupPolicyId'}}
dashboard.networks.createNetworkGroupPolicy(networkId=net['id'], name=name, **upd)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreSwitchPortSchedules(net, dashboard, path, logger):
"""
Function to restore a network's switch port group policies.
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "switch", "operation": "restoreSwitchPortSchedules", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/switch/switch_settings/port_schedules.json') as fp:
data = json.load(fp)
fp.close()
operation['restorePayload']=data
existing_port_schedules = dashboard.switch.getNetworkSwitchPortSchedules(networkId=net['id'])
# CHECK IF PORT SCHEDULE EXISTS
# IF IT DOES, JUST UPDATE
for schedule in data:
update_flag = False
for sched in existing_port_schedules:
if schedule['name'] == sched['name']:
update_flag = True
port_schedule_id = sched['id']
break
if update_flag == True:
upd = {k: schedule[k] for k in schedule.keys() - {'id', 'networkId'}}
dashboard.switch.updateNetworkSwitchPortSchedule(networkId=net['id'], portScheduleId=port_schedule_id, **upd)
else:
name = schedule['name']
upd = {k: schedule[k] for k in schedule.keys() - {'id', 'networkId', 'name'}}
dashboard.switch.createNetworkSwitchPortSchedule(networkId=net['id'], name=name, **upd)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreSwitchQos(net, dashboard, path, logger):
"""
Function to restore a network's switch qos policies.
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "switch", "operation": "restoreSwitchQos", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/switch/switch_settings/qos_rules.json') as fp:
data = json.load(fp)
fp.close()
operation['restorePayload']=data
existing_qos_rules = dashboard.switch.getNetworkSwitchQosRules(networkId=net['id'])
# CHECK IF QOS RULE EXISTS
# IF IT DOES, DELETE THEN CREATE
for rule in existing_qos_rules:
dashboard.switch.deleteNetworkSwitchQosRule(networkId=net['id'], qosRuleId=rule['id'])
for rule in data:
vlan = rule['vlan']
upd = {k: rule[k] for k in rule.keys() - {'id', 'vlan'}}
if upd['srcPort']==None:
del upd['srcPort']
if upd['dstPort']==None:
del upd['dstPort']
dashboard.switch.createNetworkSwitchQosRule(networkId=net['id'], vlan=vlan, **upd)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreSwitchOspf(net, dashboard, path, logger):
"""
Function to restore a network's switch OSPF settings.
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "switch", "operation": "restoreSwitchOspf", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/switch/switch_routing/ospf.json') as fp:
data = json.load(fp)
fp.close()
operation['restorePayload']=data
if data['v3']['enabled']==False:
del data['v3']
dashboard.switch.updateNetworkSwitchRoutingOspf(networkId=net['id'], **data)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreSwitchAccessPolicies(net, dashboard, path, logger):
"""
Function to restore a network's switch access policies.
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "switch", "operation": "restoreSwitchAccessPolicies", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/switch/switch_settings/access_policies.json') as fp:
data = json.load(fp)
fp.close()
operation['restorePayload']=data
existing_access_policies = dashboard.switch.getNetworkSwitchAccessPolicies(networkId=net['id'])
# CHECK IF ACCESS POLICY EXISTS
# IF IT DOES, JUST UPDATE
for policy in data:
update_flag = False
policy_keys = policy.keys()
for ap in existing_access_policies:
if policy['name'] == ap['name']:
update_flag = True
break
if update_flag == True:
access_policy_number = policy['accessPolicyNumber']
name = policy['name']
radius_auth_servers = []
if 'radiusServers' in policy_keys:
radius_auth_servers = policy['radiusServers']
for auth_server in radius_auth_servers:
auth_server['secret'] = input(f"Please input your desired RADIUS authentication secret for Access Policy {name} and server {auth_server['host']}: ")
if 'radiusAccountingServers' in policy_keys:
radius_acct_servers = policy['radiusAccountingServers']
for acct_server in radius_acct_servers:
acct_server['secret'] = input(f"Please input your desired RADIUS accounting secret for Access Policy {name} and server {acct_server['host']}: ")
radius_testing = policy['radiusTestingEnabled']
if radius_testing==None:
radius_testing=False
radius_coa_support = policy['radiusCoaSupportEnabled']
if radius_coa_support==None:
radius_coa_support=False
radius_acct_enabled = policy['radiusAccountingEnabled']
if radius_acct_enabled==None:
radius_acct_enabled=False
host_mode = policy['hostMode']
url_redirect_walled_garden_enabled = policy['urlRedirectWalledGardenEnabled']
if url_redirect_walled_garden_enabled==None:
url_redirect_walled_garden_enabled=False
upd = {k: policy[k] for k in policy.keys() - {
'accessPolicyNumber',
'name',
'radiusServers',
'radiusTestingEnabled',
'radiusCoaSupportEnabled',
'radiusAccountingEnabled',
'hostMode',
'urlRedirectWalledGardenEnabled'
}}
dashboard.switch.updateNetworkSwitchAccessPolicy(
networkId=net['id'],
accessPolicyNumber=access_policy_number,
name=name,
radiusServers=radius_auth_servers,
radiusTestingEnabled=radius_testing,
radiusCoaSupportEnabled=radius_coa_support,
radiusAccountingEnabled=radius_acct_enabled,
hostMode=host_mode,
urlRedirectWalledGardenEnabled=url_redirect_walled_garden_enabled,
**upd
)
else:
access_policy_number=policy['accessPolicyNumber']
name = policy['name']
radius_auth_servers = []
if 'radiusServers' in policy_keys:
radius_auth_servers = policy['radiusServers']
for auth_server in radius_auth_servers:
auth_server['secret'] = input(f"Please input your desired RADIUS authentication secret for Access Policy {name} and server {auth_server['host']}: ")
if 'radiusAccountingServers' in policy_keys:
radius_acct_servers = policy['radiusAccountingServers']
for acct_server in radius_acct_servers:
acct_server['secret'] = input(f"Please input your desired RADIUS accounting secret for Access Policy {name} and server {acct_server['host']}: ")
radius_testing = policy['radiusTestingEnabled']
if radius_testing == None:
radius_testing = False
radius_coa_support = policy['radiusCoaSupportEnabled']
if radius_coa_support == None:
radius_coa_support = False
radius_acct_enabled = policy['radiusAccountingEnabled']
if radius_acct_enabled == None:
radius_acct_enabled = False
host_mode = policy['hostMode']
url_redirect_walled_garden_enabled = policy['urlRedirectWalledGardenEnabled']
if url_redirect_walled_garden_enabled==None:
url_redirect_walled_garden_enabled=False
upd = {k: policy[k] for k in policy.keys() - {
'accessPolicyNumber',
'name',
'radiusServers',
'radiusTestingEnabled',
'radiusCoaSupportEnabled',
'radiusAccountingEnabled',
'hostMode',
'urlRedirectWalledGardenEnabled'
}}
dashboard.switch.createNetworkSwitchAccessPolicy(
networkId=net['id'],
name=name,
radiusServers=radius_auth_servers,
radiusTestingEnabled=radius_testing,
radiusCoaSupportEnabled=radius_coa_support,
radiusAccountingEnabled=radius_acct_enabled,
hostMode=host_mode,
urlRedirectWalledGardenEnabled=url_redirect_walled_garden_enabled,
**upd
)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreMxVlansBatch(org, net, dashboard, path, logger):
"""
Function to restore a network's MX VLANs.
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "appliance", "operation": "restoreMxVlansBatch", "restorePayload": "","status": ""}
try:
# Open VLAN settings
with open(f'{path}/network/{net["name"]}/appliance/vlans/vlan_config.json') as fp:
data = json.load(fp)
fp.close()
existing_vlans = dashboard.appliance.getNetworkApplianceVlans(networkId=net['id'])
actions = []
for i in range(len(data)):
# Since VLAN 1 always exists in a new config, this must be updated
# Trying to create it gives an error
if data[i]['id'] == 1:
action = {
"resource": f'/networks/{net["id"]}/appliance/vlans/{data[i]["id"]}',
"operation": 'update',
"body": {k: data[i][k] for k in data[i].keys() - {'id', 'networkId'}}
}
actions.append(action)
# For all other VLANs create them
# CHECK IF VLANS ALREADY EXIST
# IF THEY DO, JUST UPDATE
else:
update_flag = False
for j in range(len(existing_vlans)):
if data[i]['id']==existing_vlans[j]['id']:
update_flag = True
break
if update_flag==True:
action = {
"resource": f'/networks/{net["id"]}/appliance/vlans/{data[i]["id"]}',
"operation": 'update',
"body": {k: data[i][k] for k in data[i].keys() - {'id', 'networkId'}}
}
actions.append(action)
else:
action = {
"resource": f'/networks/{net["id"]}/appliance/vlans',
"operation": 'create',
"body": {k: data[i][k] for k in data[i].keys() - {'networkId'}}
}
actions.append(action)
with open(f'{path}/network/{net["name"]}/appliance/vlans/vlan_ports.json') as fp:
data = json.load(fp)
fp.close()
devices = dashboard.networks.getNetworkDevices(networkId=net['id'])
for device in devices:
if device['model'] in ['MX64', 'MX64W', 'MX67', 'MX67W', 'MX67C', 'MX100']:
starting_port = 2
elif 'MX' in device['model']:
starting_port = 3
model_ports = dashboard.appliance.getNetworkAppliancePorts(networkId=net['id'])
# If trying to apply a backup to an MX with fewer ports stop at the last port
if len(data) < len(model_ports):
logger.info("MX has more ports than backup")
for i in range(len(data)):
action = {
"resource": f'/networks/{net["id"]}/appliance/ports/{i+starting_port}',
"operation": 'update',
"body": {k: data[i][k] for k in data[i].keys() - {'number'}}
}
actions.append(action)
else:
for i in range(len(model_ports)):
action = {
"resource": f'/networks/{net["id"]}/appliance/ports/{i+starting_port}',
"operation": 'update',
"body": {k: data[i][k] for k in data[i].keys() - {'number'}}
}
actions.append(action)
operation['restorePayload']=actions
# Synchronous batches may only have 20 actions, so need to split actions list in groups of 20
# Since we're grouping VLAN creation and port assignment, and port assignment depends on VLANs existing, port
# assignment must happen after VLAN creation, hence synchronously
if len(actions)<=20:
dashboard.organizations.createOrganizationActionBatch(
organizationId=org,
actions=actions,
confirmed=True,
synchronous=True
)
else:
for i in range(0, len(actions), 20):
subactions = actions[i:i+20]
batch = dashboard.organizations.createOrganizationActionBatch(
organizationId=org,
actions=subactions,
confirmed=True,
synchronous=True
)
time.sleep(1)
status = dashboard.organizations.getOrganizationActionBatch(organizationId=org,
actionBatchId=batch['id'])['status']['completed']
while status != True:
time.sleep(1)
status = dashboard.organizations.getOrganizationActionBatch(organizationId=org,
actionBatchId=batch['id'])['status']['completed']
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreMxSecurity(net, dashboard, path, logger):
"""
Function to restore a network's MX AMP and IPS settings
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "appliance", "operation": "restoreMxSecurity", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/appliance/security/amp.json') as fp:
amp_data = json.load(fp)
fp.close()
with open(f'{path}/network/{net["name"]}/appliance/security/ips.json') as fp:
ips_data = json.load(fp)
fp.close()
operation['restorePayload']=[amp_data, ips_data]
dashboard.appliance.updateNetworkApplianceSecurityIntrusion(networkId=net['id'], **ips_data)
dashboard.appliance.updateNetworkApplianceSecurityMalware(networkId=net['id'], **amp_data)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreMxFirewall(net, dashboard, path, logger):
"""
Function to restore a network's MX L3 and L7 firewall settings
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "appliance", "operation": "restoreMxFirewall", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/appliance/security/l3_fw.json') as fp:
l3_data = json.load(fp)
fp.close()
with open(f'{path}/network/{net["name"]}/appliance/security/l7_fw.json') as fp:
l7_data = json.load(fp)
fp.close()
operation['restorePayload']=[l3_data, l7_data]
dashboard.appliance.updateNetworkApplianceFirewallL3FirewallRules(networkId=net['id'], **l3_data)
dashboard.appliance.updateNetworkApplianceFirewallL7FirewallRules(networkId=net['id'], **l7_data)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreMxContentFiltering(net, dashboard, path, logger):
"""
Function to restore a network's MX Content Filtering settings
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "appliance", "operation": "restoreMxContentFiltering", "restorePayload": "","status": ""}
try:
# Read each config file and apply the config
with open(f'{path}/network/{net["name"]}/appliance/security/content_filtering.json') as fp:
data = json.load(fp)
fp.close()
operation['restorePayload']=data
dashboard.appliance.updateNetworkApplianceContentFiltering(networkId=net['id'], **data)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreMxShaping(net, dashboard, path, logger):
"""
Function to restore a network's MX Shaping settings
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "appliance", "operation": "restoreMxShaping", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/appliance/shaping/global_shaping.json') as fp:
global_data = json.load(fp)
fp.close()
with open(f'{path}/network/{net["name"]}/appliance/shaping/shaping_rules.json') as fp:
rules_data = json.load(fp)
fp.close()
operation['restorePayload']=[global_data, rules_data]
dashboard.appliance.updateNetworkApplianceTrafficShaping(networkId=net['id'], **global_data)
dashboard.appliance.updateNetworkApplianceTrafficShapingRules(networkId=net['id'], **rules_data)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreMxVpnConfig(net, dashboard, path, logger):
"""
Function to restore a network's MX VPN settings
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "appliance", "operation": "restoreMxVpnConfig", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/appliance/vpn_config/vpn_config.json') as fp:
data = json.load(fp)
fp.close()
operation['restorePayload']=data
mode = data['mode']
upd = {k: data[k] for k in data.keys() - {'mode'}}
dashboard.appliance.updateNetworkApplianceVpnSiteToSiteVpn(networkId=net['id'], mode=mode, **upd)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreSwitchPortConfigsBatch(org, net, dashboard, path, devices_in_network, logger):
"""
Function to restore a network's Switch Port settings
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "switch", "operation": "restoreSwitchPortConfigsBatch", "restorePayload": "","status": ""}
try:
directory = f'{path}/network/{net["name"]}/switch/switch_settings'
port_schedules = dashboard.switch.getNetworkSwitchPortSchedules(networkId=net['id'])
access_policies = dashboard.switch.getNetworkSwitchAccessPolicies(networkId=net['id'])
# For each switch subfolder, read and update port configs
actions = []
for subdirs, dirs, files in os.walk(directory):
for dir in dirs:
if dir not in [device['serial'] for device in devices_in_network]:
logger.info(f"Your backup contains switch port configs for {dir}, but this device is not currently in the network.")
logger.info(f"Switch port settings for {dir} will not be restored.")
else:
with open(f'{path}/network/{net["name"]}/switch/switch_settings/{dir}/switch_ports.json') as fp:
data = json.load(fp)
fp.close()
for port in data:
upd = port
for schedule in port_schedules:
if schedule['name']==upd['portScheduleId']:
upd['portScheduleId']=schedule['id']
if port['type'] == 'access':
if port['accessPolicyType'] != 'Open':
for policy in access_policies:
if policy['name'] == port['accessPolicyNumber']:
upd['accessPolicyNumber']=int(policy['accessPolicyNumber'])
action = {
"resource": f'/devices/{dir}/switch/ports/{upd["portId"]}',
"operation": 'update',
"body": {k: upd[k] for k in upd.keys() - {'portId'}}
}
actions.append(action)
operation['restorePayload']=actions
for i in range(0, len(actions), 100):
subactions = actions[i:i + 100]
dashboard.organizations.createOrganizationActionBatch(
organizationId=org,
actions=subactions,
confirmed=True,
synchronous=False
)
time.sleep(1)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreNetworkAlerts(net, dashboard, path, logger):
"""
Function to restore a network's alerts.
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "network", "operation": "restoreNetworkAlerts", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/alert_settings/alerts.json') as fp:
data = json.load(fp)
fp.close()
dashboard.networks.updateNetworkAlertsSettings(networkId=net['id'], defaultDestinations=data['defaultDestinations'], alerts=data['alerts'])
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreMrSsidConfigs(net, dashboard, path, logger):
"""
Function to restore a network's SSIDs
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "wireless", "operation": "restoreMrSsidConfigs", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/wireless/ssid_settings/ssids.json') as fp:
data = json.load(fp)
fp.close()
current_ssids = dashboard.wireless.getNetworkWirelessSsids(networkId=net['id'])
for ssid in current_ssids:
print(ssid)
operation['restorePayload'] = data
for ssid in data:
if 'Unconfigured SSID' not in ssid['name']:
upd = ssid
ssid_number = ssid['number']
del upd['number']
ssid_keys = upd.keys()
if 'authMode' in ssid_keys:
#if ssid['authMode']=='psk':
# ssid['psk']=input(f"Please input your desired PSK for SSID {ssid['name']}: ")
if ssid['authMode']=='8021x-radius':
if ssid['wpaEncryptionMode']=='WPA3 192-bit Security':
ssid['wpaEncryptionMode']='WPA3 only'
if 'radiusServers' in ssid_keys:
for auth_server in ssid['radiusServers']:
auth_server['secret'] = input(f"Please input your desired RADIUS authentication secret for SSID {ssid['name']} and server {auth_server['host']}: ")
if 'radiusAccountingServers' in ssid_keys:
for acct_server in ssid['radiusAccountingServers']:
acct_server['secret'] = input(f"Please input your desired RADIUS accounting secret for SSID {ssid['name']} and server {acct_server['host']}: ")
if upd['authMode']!='psk' and upd['authMode']!='open':
del upd['encryptionMode']
delete_keys=[]
for key in upd.keys():
if upd[key]==None:
delete_keys.append(key)
for key in delete_keys:
del upd[key]
dashboard.wireless.updateNetworkWirelessSsid(networkId=net['id'],number=ssid_number,**upd)
operation['status'] = "Complete"
except meraki.APIError as e:
logger.error(e)
operation['status'] = e
except Exception as e:
logger.error(e)
operation["status"]=e
return operation
def restoreMrRfProfiles(net, dashboard, path, devices_in_network, logger):
"""
Function to restore a network's RF Profiles
:param net: target network
:param dashboard: Meraki API client
:param path: Backup location
:return:
"""
operation = {"network": net, "operation_type": "wireless", "operation": "restoreMrRfProfiles", "restorePayload": "","status": ""}
try:
with open(f'{path}/network/{net["name"]}/wireless/radio_settings/rf_profiles.json') as fp:
data = json.load(fp)
fp.close()
operation['restorePayload']=data
existing_profiles = dashboard.wireless.getNetworkWirelessRfProfiles(networkId=net['id'])
for rf_profile in data:
update_flag = False
for profile in existing_profiles:
if rf_profile['name']==profile['name']:
update_flag = True
profile_id = profile['id']
profile_name = profile['name']
break
if update_flag == True:
upd = rf_profile
band_selection_type = rf_profile['bandSelectionType']
if upd['fiveGhzSettings']['minPower'] < 8:
upd['fiveGhzSettings']['minPower'] = 8
logger.warning('Minimum power configurable for 5GHz via API is 8')
if upd['fiveGhzSettings']['maxPower'] > 30:
upd['fiveGhzSettings']['maxPower'] = 30