-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsd-wan-exim.py
executable file
·1597 lines (1289 loc) · 59 KB
/
sd-wan-exim.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Cisco SD-WAN EXIM (Export and Import) Console Script.
Copyright (c) 2019 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance with the terms of
the License. All rights not expressly granted by the License are
reserved. Unless required by applicable law or agreed to separately in
writing, software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied.
Command line tool for Cisco SD-WAN vManage configuration management.
Example: python sd-wan-exim.py <vManage> <username> <password> <action>
Actions:
export Export entire configuration.
configure Import entire configuration.
configure_policies Import policies, definitions and lists.
configure_templates Import feature templates and device templates.
clean Delete template(all) and policy(all) configuration.
clean_policies Delete (only) policies, definitions and lists.
clean_templates Delete (only) device and feature templates.
clean_devices Delete certificates and system devices.
password Update user password
add_user Add user
invalidate_certificates Invalidate device certificates
validate_certificates Validate device certificates
push_to_controllers Push configuration to controllers
detach_devices Detach device templates
deactivate_policies Deactivate policies
"""
from __future__ import print_function
from pprint import pprint
from collections import OrderedDict
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import requests
import sys
import json
import argparse
import tarfile
import glob
import os
import shutil
import time
import re
import urllib.parse
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
__author__ = "Octavian Preda"
__email__ = "[email protected]"
__version__ = "1.6.0"
__copyright__ = "Copyright (c) 2020 Cisco and/or its affiliates."
__license__ = "Cisco Sample Code License, Version 1.1"
__status__ = "Development"
""" GLOBAL VARIABLES """
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
CONFIG_ARCH = "config_archive.tar.gz"
ITEM_DIC = {
"device_template" : ("template/device", "templateId"),
"feature_template" : ("template/feature", "templateId"),
"vedge_policy" : ("template/policy/vedge", "policyId"),
"vsmart_policy" : ("template/policy/vsmart", "policyId"),
"security_policy" : ("template/policy/security", "policyId"),
"policy_definition" : ("template/policy/definition", "definitionId"),
"policy_list" : ("template/policy/list", "listId"),
"system_device" : ("system/device/vedges", "uuid")
}
class CiscoException(Exception):
pass
class rest_api_lib:
def __init__(self, vmanage_ip, username, password):
self.vmanage_ip = vmanage_ip
self.headers = {}
self.session = requests.session()
self.login(self.vmanage_ip, username, password)
def login(self, vmanage_ip, username, password):
"""Login to vmanage"""
base_url_str = 'https://{0}/'.format(vmanage_ip)
login_str = 'j_security_check'
token_str = 'dataservice/client/token'
#Url for posting login data
login_url = base_url_str + login_str
token_url = base_url_str + token_str
#Format data for loginForm
login_data = {'j_username' : username, 'j_password' : password}
#If the vmanage has a certificate signed by a trusted authority change verify to True
login_response = self.session.post(url=login_url, data=login_data, verify=False)
if b'<html>' in login_response.content or login_response.status_code != 200:
raise CiscoException('Login Failed: {0}'.format(login_response.status_code))
#If the vmanage has a certificate signed by a trusted authority change verify to True
token_response = self.session.get(url=token_url, verify=False)
if token_response.status_code == 200:
self.headers['X-XSRF-TOKEN'] = token_response.content
elif token_response.status_code == 404:
pass
else:
raise CiscoException('Failed getting X-XSRF-TOKEN: {0}'.format(token_response.status_code))
def get_request(self, mount_point):
"""GET request"""
url = "https://%s/dataservice/%s"%(self.vmanage_ip, mount_point)
response = self.session.get(url, headers=self.headers, verify=False)
#response.raise_for_status()
data = response.content
return data
def post_request(self, mount_point, payload):
"""POST request"""
url = "https://%s/dataservice/%s"%(self.vmanage_ip, mount_point)
dup_template_msg = "Template with name"
dup_list_msg = "Duplicate policy list entry"
dup_policy_msg = "Duplicate policy detected with name"
dup_vedge_msg = "vEdge policy with name"
dup_vsmart_msg = "vSmart policy with name"
dup_token = "Umbrella Token entry already exists"
dup_key = "Threat Grid Api key entry already exists"
version_msg = "Failed to create definition"
unknown_msg = "Unknown error"
payload = json.dumps(payload)
self.headers['Content-Type'] = 'application/json'
response = self.session.post(url=url, data=payload, headers=self.headers, verify=False)
if response.status_code != 200:
if (response.status_code == 400):
response_details = str(response.json()['error']['details'])
if (response_details.startswith(dup_template_msg)) or \
(response_details.startswith(dup_list_msg)) or \
(response_details.startswith(dup_policy_msg)) or \
(response_details.startswith(dup_vedge_msg)) or \
(response_details.startswith(dup_vsmart_msg)) or \
(response_details.startswith(dup_token)) or \
(response_details.startswith(dup_key)) or \
(response_details.startswith(version_msg)) or \
(response_details.startswith(unknown_msg)):
return response_details
else:
try:
print(response_details)
except:
print(response)
raise CiscoException("Fail - Post")
try:
data = response.json()
except ValueError:
data = "Successful"
return data
def put_request(self, mount_point, payload):
"""PUT request"""
url = "https://%s/dataservice/%s"%(self.vmanage_ip, mount_point)
payload = json.dumps(payload)
self.headers['Content-Type'] = 'application/json'
response = self.session.put(url=url, data=payload, headers=self.headers, verify=False)
if response.status_code != 200:
print(response.json()['error']['details'])
raise CiscoException("Fail - Put")
try:
data = response.json()
except ValueError:
data = "Successful"
return data
def delete_request(self, mount_point):
"""DELETE request"""
url = "https://%s/dataservice/%s"%(self.vmanage_ip, mount_point)
factory_template_msg = "Template is a factory default"
policy_list_ro_msg = "This policy list is a read only list and it cannot be deleted"
policy_list_partner = "This policy list is created by a partner and can only be removed when the partner is deleted."
response = self.session.delete(url=url, headers=self.headers, verify=False)
data = response.content
#print(response.status_code)
if response.status_code != 200:
if (response.status_code == 400):
if (response.json()['error']['details'] == factory_template_msg):
return(response.json()['error']['details'])
elif(response.json()['error']['details'] == policy_list_ro_msg):
return(response.json()['error']['details'])
elif(response.json()['error']['details'] == policy_list_partner):
return(response.json()['error']['details'])
else:
print(response.json()['error']['details'])
raise CiscoException("Fail - Delete")
else:
print(response)
raise CiscoException("Fail - Delete")
if data:
return data
else:
return "Successful"
def use_tenant(self, tenant):
print("tenant")
mount_point = "tenant"
response = json.loads(sdwanp.get_request(mount_point))
device_data = response["data"]
tenant_id = ""
for device in device_data:
if device["name"] == tenant:
tenant_id = device["tenantId"]
if not tenant_id:
raise CiscoException("Tenant {} not found! Please check tenant name and try again.".format(tenant))
item = {}
mount_point = "tenant/" + str(tenant_id) + "/switch"
response = sdwanp.post_request(mount_point, item)
self.headers["VSessionId"] = response["VSessionId"]
def get_ids(generic_item):
mount_point, key_id = ITEM_DIC[generic_item]
response = json.loads(sdwanp.get_request(mount_point))
device_data = response['data']
return [device[key_id] for device in device_data]
def get_policy_definition_ids(mount_point):
new_mount_point = "template/policy/definition" + str(mount_point)
response = sdwanp.get_request(new_mount_point)
if response:
response = json.loads(response)
device_data = response['data']
return [device["definitionId"] for device in device_data]
else:
return []
def get_policy_list_ids(mount_point):
new_mount_point = "template/policy/list" + str(mount_point)
response = sdwanp.get_request(new_mount_point)
if response:
response = json.loads(response)
device_data = response['data']
return [device["listId"] for device in device_data]
else:
return []
def update_ids(item, list_id_old, list_id_new):
def replace_id(match):
matched_id = match.group(0)
if matched_id in list_id_old:
old_id = list_id_old[matched_id]
new_id = list_id_new[old_id]
return new_id
else:
return matched_id
dict_json = re.sub(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',
replace_id, json.dumps(item))
return json.loads(dict_json, object_pairs_hook=OrderedDict)
def load_json_from_file(fp):
with open(fp) as f:
return json.load(f, object_pairs_hook=OrderedDict)
def action_print(msg):
print("Action:")
print(msg)
print("")
def wait(minutes):
print("Waiting {} minutes".format(minutes))
for i in range(minutes, 0, -1):
time.sleep(60)
if i > 1:
print("Remaining time {} minute/minutes".format(i-1))
print("")
def export_generic_item(file_path, generic_item, mount_point):
"""Export generic_item
Data is exported as JSON in a separate folder called configuration.
"""
print(generic_item)
json_file = os.path.join(file_path, str(generic_item) + ".json")
ids_list = get_ids(generic_item)
export_data = OrderedDict({"configuration": []})
for id in ids_list:
print("Exporting ID: {}".format(id))
new_mount_point = str(mount_point) + "/" + str(id)
device_data = json.loads(sdwanp.get_request(new_mount_point))
if device_data:
export_data["configuration"].append(device_data)
with open(json_file, 'w') as f:
json.dump(export_data, f)
def export_generic_policy_ids(file_path, generic_item, mount_point):
"""Export generic_item IDs
Data is exported as JSON in a separate folder called configuration.
"""
print(generic_item)
json_file = os.path.join(file_path, str(generic_item) + ".json")
export_data = OrderedDict({"configuration": []})
device_data = json.loads(sdwanp.get_request(mount_point))
if device_data:
export_data["configuration"] = device_data
with open(json_file, 'w') as f:
json.dump(export_data, f)
def export_policy_definitions(file_path):
"""Export policy definitions
Data is exported as JSON in a separate folder called configuration.
"""
print("policy_definition")
policy_definition_json_file = os.path.join(file_path, "policy_definition.json")
policy_definition_ids_list = OrderedDict({})
definition_mount_points = [
"/cflowd",
"/dnssecurity",
"/advancedMalwareProtection",
"/control",
"/intrusionprevention",
"/vedgeroute",
"/hubandspoke",
"/acl",
"/vpnmembershipgroup",
"/approute",
"/zonebasedfw",
"/urlfiltering",
"/qosmap",
"/aclv6",
"/mesh",
"/data",
"/rewriterule"
]
for mount_point in definition_mount_points:
try:
print("Exporting done for {0}".format(mount_point))
policy_definition_ids_list[mount_point] = get_policy_definition_ids(mount_point)
except:
print("Exporting skipped for {0}, not present".format(mount_point))
#pprint(policy_definition_ids_list)
policy_definitions = OrderedDict({"configuration": OrderedDict()})
for mount_point in definition_mount_points:
device_data_list = []
if mount_point in policy_definition_ids_list:
for id in policy_definition_ids_list[mount_point]:
print("Exporting ID: {}".format(id))
new_mount_point = "template/policy/definition" + str(mount_point) + "/" + str(id)
device_data = json.loads(sdwanp.get_request(new_mount_point))
if device_data:
device_data_list.append(device_data)
policy_definitions["configuration"][mount_point] = device_data_list
with open(policy_definition_json_file, 'w') as f:
json.dump(policy_definitions, f)
def export_policy_lists(file_path):
"""Export policy lists
Data is exported as JSON in a separate folder called configuration.
"""
print("policy_list")
policy_list_json_file = os.path.join(file_path, "policy_list.json")
policy_list_ids_list = OrderedDict({})
list_mount_points = [
"/community",
"/localdomain",
"/dataipv6prefix",
"/ipv6prefix",
"/tloc",
"/umbrellasecret",
"/aspath",
"/zone",
"/color",
"/sla",
"/localapp",
"/app",
"/mirror",
"/dataprefix",
"/extcommunity",
"/site",
# "/ipprefixall"
"/prefix",
"/umbrelladata",
"/class",
"/ipssignature",
# "/dataprefixall",
"/urlblacklist",
"/policer",
"/urlwhitelist",
"/vpn",
"/tgapikey"
]
for mount_point in list_mount_points:
try:
print("Exporting done for {0}".format(mount_point))
policy_list_ids_list[mount_point] = get_policy_list_ids(mount_point)
except:
print("Exporting skipped for {0}, not present".format(mount_point))
#pprint(policy_definition_ids_list)
policy_lists = OrderedDict({"configuration": OrderedDict()})
for mount_point in list_mount_points:
device_data_list = []
if mount_point in policy_list_ids_list:
for id in policy_list_ids_list[mount_point]:
print("Exporting ID: {}".format(id))
new_mount_point = "template/policy/list" + str(mount_point) + "/" + str(id)
device_data = json.loads(sdwanp.get_request(new_mount_point))
if device_data:
device_data_list.append(device_data)
policy_lists["configuration"][mount_point] = device_data_list
with open(policy_list_json_file, 'w') as f:
json.dump(policy_lists, f)
def delete_generic_item(generic_item):
print(generic_item)
ids_list = get_ids(generic_item)
mount_point, key_id = ITEM_DIC[generic_item]
if (generic_item == "system_device"):
mount_point = "system/device"
for id in ids_list:
print("Deleting ID: {} - ".format(id), end="")
id = urllib.parse.quote(id, safe='')
new_mount_point = str(mount_point) + "/" + str(id)
response = sdwanp.delete_request(new_mount_point)
print(response)
print("")
def delete_policy_definitions():
print("policy_definition")
definition_mount_points = [
"/cflowd",
"/dnssecurity",
"/advancedMalwareProtection",
"/control",
"/intrusionprevention",
"/vedgeroute",
"/hubandspoke",
"/acl",
"/vpnmembershipgroup",
"/approute",
"/zonebasedfw",
"/urlfiltering",
"/qosmap",
"/aclv6",
"/mesh",
"/data",
"/rewriterule"
]
for mount_point in definition_mount_points:
policy_definition_ids_list = get_policy_definition_ids(mount_point)
for id in policy_definition_ids_list:
print("Deleting ID: {} - ".format(id), end="")
new_mount_point = "template/policy/definition" + str(mount_point)+ "/" + str(id)
response = sdwanp.delete_request(new_mount_point)
print(response)
print("")
def delete_policy_lists():
print("policy_list")
list_mount_points = [
"/community",
"/localdomain",
"/dataipv6prefix",
"/ipv6prefix",
"/tloc",
"/umbrellasecret",
"/aspath",
"/zone",
"/color",
"/sla",
"/localapp",
"/app",
"/mirror",
"/dataprefix",
"/extcommunity",
"/site",
# "/ipprefixall"
"/prefix",
"/umbrelladata",
"/class",
"/ipssignature",
# "/dataprefixall",
"/urlblacklist",
"/policer",
"/urlwhitelist",
"/vpn",
"/tgapikey"
]
for mount_point in list_mount_points:
policy_list_ids_list = get_policy_list_ids(mount_point)
for id in policy_list_ids_list:
print("Deleting ID: {} - ".format(id), end="")
new_mount_point = "template/policy/list" + str(mount_point)+ "/" + str(id)
response = sdwanp.delete_request(new_mount_point)
print(response)
print("")
def device_certificates(validity):
print("device_certificate")
mount_point = "certificate/vedge/list"
response = json.loads(sdwanp.get_request(mount_point))
device_data = response["data"]
chassis_serial_list_ids = [(device["chasisNumber"], device["serialNumber"]) for device in device_data]
for chasisNumber, serialNumber in chassis_serial_list_ids:
print("{}ating certificate chassis ID:{}... ".format(validity, chasisNumber)),
mount_point = "certificate/save/vedge/list"
item = [{"chasisNumber" : chasisNumber, "serialNumber" : serialNumber, "validity" : validity}]
response = sdwanp.post_request(mount_point, item)
print (response)
print("")
def invalidate_certificates():
"""Invalidate device certificates.
Example command:
./sd-wan-exim.py invalidate_certificates
"""
print("invalidate_certificate")
device_certificates("invalid")
def validate_certificates():
"""Validate device certificates.
Example command:
./sd-wan-exim.py validate_certificates
"""
print("validate_certificates")
device_certificates("valid")
def push_to_controllers():
"""Push configuration to controllers.
Example command:
./sd-wan-exim.py push_to_controllers
"""
print("push_to_controllers")
mount_point = "certificate/vedge/list?action=push"
item = {}
response = sdwanp.post_request(mount_point, item)
print("Push to controllers: {}".format(response))
wait(2)
def detach_devices():
"""Detach devices.
Example command:
./sd-wan-exim.py detach_devices
"""
print("detach_devices")
mount_point = "template/device"
mount_point_attach = "template/config/device/mode/cli"
response = json.loads(sdwanp.get_request(mount_point))
device_data = response["data"]
template_list_ids = [device["templateId"] for device in device_data]
need_to_wait = False
for template_id in template_list_ids:
mount_point = "template/device/config/attached/" + str(template_id)
response = json.loads(sdwanp.get_request(mount_point))
attach_data = response["data"]
if attach_data:
need_to_wait = True
for attach in attach_data:
item = {}
item["devices"] = []
if (attach["personality"] == 'vedge'):
print(attach["personality"], attach["uuid"], attach["deviceIP"])
item["deviceType"] = attach["personality"]
item["devices"].append({"deviceId":attach["uuid"],"deviceIP":attach["deviceIP"]})
response = sdwanp.post_request(mount_point_attach, item)
if need_to_wait:
print("Device vedge templates detached")
wait(3)
else:
print("All device vedge templates are already detached")
need_to_wait = False
for template_id in template_list_ids:
mount_point = "template/device/config/attached/" + str(template_id)
response = json.loads(sdwanp.get_request(mount_point))
attach_data = response["data"]
if attach_data:
need_to_wait = True
for attach in attach_data:
item = {}
item["devices"] = []
if (attach["personality"] == 'vsmart'):
print(attach["personality"], attach["uuid"], attach["deviceIP"])
item["deviceType"] = 'controller'
item["devices"].append({"deviceId":attach["uuid"],"deviceIP":attach["deviceIP"]})
response = sdwanp.post_request(mount_point_attach, item)
if need_to_wait:
print("Device vsmart templates detached")
wait(2)
else:
print("All device vsmart templates are already detached")
def deactivate_generic_policy(mount_point):
response = json.loads(sdwanp.get_request(mount_point))
device_data = response['data']
policy_active_ids = [device["policyId"] for device in device_data if device["isPolicyActivated"] == True]
need_to_wait = False
for policy_active_id in policy_active_ids:
need_to_wait = True
new_mount_point = mount_point + "/deactivate/" + str(policy_active_id)
item = {}
response = sdwanp.post_request(new_mount_point, item)
print("Deactivated policy:{} - {}".format(policy_active_id, response))
if need_to_wait:
print("Policies deactivated")
wait(2)
else:
print("All policies are already deactivated")
def deactivate_policies():
"""Deactivate policies.
Example command:
./sd-wan-exim.py deactivate_policies
"""
print("deactivate_policies")
deactivate_generic_policy("template/policy/vsmart")
#deactivate_generic_policy("template/policy/security")
def check_attached_devices():
print("check_attached_devices")
mount_point = "template/device"
response = json.loads(sdwanp.get_request(mount_point))
device_data = response["data"]
template_list_ids = [device["templateId"] for device in device_data]
for template_id in template_list_ids:
mount_point = "template/device/config/attached/" + str(template_id)
response = json.loads(sdwanp.get_request(mount_point))
attach_data = response["data"]
if attach_data:
return True
return False
def import_feature_templates(file_path):
print("feature_template")
feature_template_json_file = os.path.join(file_path, "feature_template.json")
if not os.path.exists(feature_template_json_file):
print("No feature templates")
print("")
return (OrderedDict(), OrderedDict())
feature_data = load_json_from_file(feature_template_json_file)
feature_template_data = feature_data["configuration"]
for item in feature_template_data:
'''
if "templateDefinition" in item:
if "vrrp" in item["templateDefinition"]:
print("ATTENTION: VRRP SKIPPED - Featute Template imported and VRRP set to Empty")
item["templateDefinition"]["vrrp"] = {}
'''
mount_point = "template/feature/"
print("Feature template: Importing {0} - ".format(item["templateName"]), end="")
response = sdwanp.post_request(mount_point, item)
print("Done, {0}".format(response))
""" Update Feature IDs """
feature_template_id_old = OrderedDict()
for item in feature_template_data:
feature_template_id_old[item['templateId']] = item['templateName']
feature_template_id_new = OrderedDict()
response = json.loads(sdwanp.get_request('template/feature'))
feature_template_data = response['data']
for feature_template_temp in feature_template_data:
feature_template_id_new[feature_template_temp['templateName']] = feature_template_temp['templateId']
print("")
return (feature_template_id_old, feature_template_id_new)
def import_device_templates(file_path, all_template_ids, all_policy_ids = ([],[],[],[],[],[])):
print("device_template")
f_t_old, f_t_new = all_template_ids
ve_t_old, ve_t_new, vs_t_old, vs_t_new, sec_t_old, sec_t_new = all_policy_ids
device_template_json_file = os.path.join(file_path, "device_template.json")
if not os.path.exists(device_template_json_file):
print("No device templates")
print("")
return (OrderedDict(), OrderedDict())
device_template = load_json_from_file(device_template_json_file)
device_template_data = device_template["configuration"]
for item in device_template_data:
if "configType" in item:
if item["configType"] == "template":
mount_point = "template/device/feature"
item["featureTemplateUidRange"] = []
try:
del item["templateId"]
except:
pass
""" Update policy IDs """
if "policyId" in item:
if item["policyId"] in ve_t_old:
old_aux = ve_t_old[item["policyId"]]
new_aux = ve_t_new[old_aux]
item["policyId"] = new_aux
elif item["policyId"] in vs_t_old:
old_aux = vs_t_old[item["policyId"]]
new_aux = vs_t_new[old_aux]
item["policyId"] = new_aux
elif item["policyId"] in sec_t_old:
old_aux = sec_t_old[item["policyId"]]
new_aux = sec_t_new[old_aux]
item["policyId"] = new_aux
else:
item["policyId"] = ""
else:
item["policyId"] = ""
""" Update security policy IDs """
if "securityPolicyId" in item:
if item["securityPolicyId"] in ve_t_old:
old_aux = ve_t_old[item["securityPolicyId"]]
new_aux = ve_t_new[old_aux]
item["securityPolicyId"] = new_aux
elif item["securityPolicyId"] in vs_t_old:
old_aux = vs_t_old[item["securityPolicyId"]]
new_aux = vs_t_new[old_aux]
item["securityPolicyId"] = new_aux
elif item["securityPolicyId"] in sec_t_old:
old_aux = sec_t_old[item["securityPolicyId"]]
new_aux = sec_t_new[old_aux]
item["securityPolicyId"] = new_aux
else:
item["securityPolicyId"] = ""
else:
item["securityPolicyId"] = ""
""" Update generalTemplates IDs """
if "generalTemplates" in item:
for i in range(0, len(item["generalTemplates"])):
template_id = item["generalTemplates"][i]["templateId"]
old_aux = f_t_old[template_id]
new_aux = f_t_new[old_aux]
item["generalTemplates"][i]["templateId"] = new_aux
""" Update subtemplates generalTemplates IDs """
if "subTemplates" in item["generalTemplates"][i]:
for j in range(0, len(item["generalTemplates"][i]["subTemplates"])):
subtemplate_id = item["generalTemplates"][i]["subTemplates"][j]["templateId"]
old_aux = f_t_old[subtemplate_id]
new_aux = f_t_new[old_aux]
item["generalTemplates"][i]["subTemplates"][j]["templateId"] = new_aux
""" Update subsubtemplates generalTemplates IDs """
if "subTemplates" in item["generalTemplates"][i]["subTemplates"][j]:
for k in range(0, len(item["generalTemplates"][i]["subTemplates"][j]["subTemplates"])):
subsubtemple_id = item["generalTemplates"][i]["subTemplates"][j]["subTemplates"][k]["templateId"]
old_aux = f_t_old[subsubtemple_id]
new_aux = f_t_new[old_aux]
item["generalTemplates"][i]["subTemplates"][j]["subTemplates"][k]["templateId"] = new_aux
if item["deviceType"] == "vbond":
item["deviceType"] = "vedge-cloud"
print("Device template: Importing {0} - ".format(item["templateName"]), end="")
response = sdwanp.post_request(mount_point, item)
print("Done, {0}".format(response))
elif item["configType"] == "file":
try:
del item["templateId"]
del item["feature"]
del item["lastUpdatedBy"]
del item["lastUpdatedOn"]
del item["createdOn"]
del item["createdBy"]
del item["@rid"]
except:
pass
mount_point = "template/device/cli"
if item["deviceType"] == "vbond":
item["deviceType"] = "vedge-cloud"
print("Device template: Importing {0} - ".format(item["templateName"]), end="")
response = sdwanp.post_request(mount_point, item)
print("Done, {0}".format(response))
else:
print("Device template: {0} is not a template, acutal configType is {1}".format(item["templateName"], item["configType"]))
print("")
def import_policy_lists(file_path):
print("policy_list")
policy_list_json_file = os.path.join(file_path, "policy_list.json")
if not os.path.exists(policy_list_json_file):
print("No policy list")
print("")
return (OrderedDict(), OrderedDict())
policy_list = load_json_from_file(policy_list_json_file)
policy_list_data = policy_list["configuration"]
for list in policy_list_data:
mount_point = "template/policy/list" + str(list)
for item in policy_list_data[list]:
print("Policy list: Importing {0} {1} - ".format(list, item["name"]), end="")
response = sdwanp.post_request(mount_point, item)
print("Done, {0}".format(response))
print("")
list_mount_points = [
"/community",
"/localdomain",
"/dataipv6prefix",
"/ipv6prefix",
"/tloc",
"/umbrellasecret",
"/aspath",
"/zone",
"/color",
"/sla",
"/localapp",
"/app",
"/mirror",
"/dataprefix",
"/extcommunity",
"/site",
# "/ipprefixall"
"/prefix",
"/umbrelladata",
"/class",
"/ipssignature",
# "/dataprefixall",
"/urlblacklist",
"/policer",
"/urlwhitelist",
"/vpn",
"/tgapikey"
]
""" Update List IDs """
policy_list_id_old = OrderedDict()
for list in policy_list_data:
for item in policy_list_data[list]:
composed_name = str(list) + "/" + str(item['name'])
policy_list_id_old[item['listId']] = composed_name
#pprint(policy_list_id_old)
policy_list_id_new = OrderedDict()
for mount_point in list_mount_points:
response_json = sdwanp.get_request('template/policy/list' + str(mount_point))
if response_json:
response = json.loads(response_json)
policy_list_data = response['data']
for policy_list_temp in policy_list_data:
policy_list_id_new[str(mount_point) + "/" + str(policy_list_temp['name'])] = policy_list_temp['listId']
#pprint(policy_list_id_new)
return (policy_list_id_old, policy_list_id_new)
def import_policy_definitions(file_path, all_list_ids):
print("policy_definition")
policy_list_id_old, policy_list_id_new = all_list_ids
policy_definition_json_file = os.path.join(file_path, "policy_definition.json")
if not os.path.exists(policy_definition_json_file):
print("No policy definition")
print("")
return (OrderedDict(), OrderedDict())
policy_definition = load_json_from_file(policy_definition_json_file)
policy_definition_data = policy_definition["configuration"]
policy_definition_data = update_ids(policy_definition_data, policy_list_id_old, policy_list_id_new)
for definition in policy_definition_data:
mount_point = "template/policy/definition" + str(definition)
for item in policy_definition_data[definition]:
print("Policy definition: Importing {0} {1} - ".format(definition, item["name"]), end="")
response = sdwanp.post_request(mount_point, item)
print("Done, {0}".format(response))
print("")
definition_mount_points = [
"/cflowd",
"/dnssecurity",
"/advancedMalwareProtection",
"/control",
"/intrusionprevention",
"/vedgeroute",
"/hubandspoke",
"/acl",
"/vpnmembershipgroup",
"/approute",
"/zonebasedfw",
"/urlfiltering",
"/qosmap",
"/aclv6",
"/mesh",
"/data",
"/rewriterule"
]