-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVMCImportExport.py
More file actions
executable file
·3825 lines (3505 loc) · 193 KB
/
VMCImportExport.py
File metadata and controls
executable file
·3825 lines (3505 loc) · 193 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SDDC Import/Export for VMware Cloud on AWS
################################################################################
### Copyright 2020-2023 VMware, Inc.
### SPDX-License-Identifier: BSD-2-Clause
################################################################################
import configparser # parsing config file
import datetime
import glob
import json
import random
import requests # need this for Get/Post/Delete
import os
import re
import time
import sys
import boto3
from pathlib import Path
from prettytable import PrettyTable
from zipfile import ZipFile
import vmc_auth
class VMCImportExport:
"""A class to handle importing and exporting portions of a VMC SDDC"""
def __init__(self,configPath="./config_ini/config.ini", vmcConfigPath="./config_ini/vmc.ini", awsConfigPath="./config/aws.ini", vCenterConfigPath="./config_ini/vcenter.ini"):
self.vmc_auth = None
self.proxy_url = None
self.proxy_url_short = None
self.lastJSONResponse = None
self.source_org_display_name = ""
self.dest_org_display_name = ""
self.source_sddc_name = ""
self.source_sddc_version = ""
self.source_sddc_state = ""
self.source_sddc_info = ""
self.source_sddc_nsx_info = ""
self.source_sddc_nsx_csp_url = ""
self.source_sddc_enable_nsx_advanced_addon = False
self.sddc_info_hide_sensitive_data = True
self.gov_cloud_urls = False
self.dest_sddc_name = ""
self.dest_sddc_version = ""
self.dest_sddc_state = ""
self.dest_sddc_enable_nsx_advanced_addon = False
self.configPath = configPath
self.vmcConfigPath = vmcConfigPath
self.awsConfigPath = awsConfigPath
self.vCenterConfigPath = vCenterConfigPath
self.export_folder = ""
self.import_folder = ""
self.sync_mode = False
self.export_path = ""
self.import_path = ""
self.append_sddc_id_to_zip = False
self.export_zip_name = ""
self.export_history = False
self.export_purge_before_run = False
self.export_purge_after_zip = False
self.max_export_history_files = 10
self.export_type = 'os'
self.aws_s3_export_access_id = ""
self.aws_s3_export_access_secret = ""
self.aws_s3_export_bucket = ""
self.cgw_groups_import_error_dict = {}
self.cgw_groups_import_exclude_list = []
self.cgw_import_exclude_list = []
self.mgw_groups_import_exclude_list = []
self.mgw_import_exclude_list = []
self.network_import_exclude_list = []
self.export_vcenter_folders = False
self.import_vcenter_folders = False
self.export_vcenter_catagories = False
self.import_vcenter_catagories = False
self.export_vcenter_tags = False
self.import_vcenter_tags = False
self.user_search_results_json = ""
self.convertedServiceRolePayload = ""
self.RoleSyncSourceUserEmail = ""
self.RoleSyncDestUserEmails = {}
self.aws_import_access_key_id = ""
self.aws_import_secret_access_key = ""
self.aws_import_session_token = ""
self.aws_dest_sddc_region = ""
self.ConfigLoader()
def ConfigLoader(self):
"""Load all configuration variables from config.ini"""
config = configparser.ConfigParser()
vmcConfig = configparser.ConfigParser()
awsConfig = configparser.ConfigParser()
vCenterConfig = configparser.ConfigParser()
config.read(self.configPath)
vmcConfig.read(self.vmcConfigPath)
awsConfig.read(self.awsConfigPath)
vCenterConfig.read(self.vCenterConfigPath)
self.gov_cloud_urls = self.loadConfigFlag(vmcConfig,"vmcConfig","gov_cloud_urls")
if self.gov_cloud_urls is True:
self.strProdURL = vmcConfig.get("vmcConfig", "strGovProdURL")
self.strCSPProdURL = vmcConfig.get("vmcConfig", "strGovCSPProdURL")
else:
self.strProdURL = vmcConfig.get("vmcConfig", "strProdURL")
self.strCSPProdURL = vmcConfig.get("vmcConfig", "strCSPProdURL")
self.vmc_auth = vmc_auth.VMCAuth(strCSPProdURL=self.strCSPProdURL)
self.source_refresh_token = vmcConfig.get("vmcConfig", "source_refresh_token")
self.source_org_id = vmcConfig.get("vmcConfig", "source_org_id")
self.source_sddc_id = vmcConfig.get("vmcConfig", "source_sddc_id")
self.dest_refresh_token = vmcConfig.get("vmcConfig", "dest_refresh_token")
self.dest_org_id = vmcConfig.get("vmcConfig", "dest_org_id")
self.dest_sddc_id = vmcConfig.get("vmcConfig", "dest_sddc_id")
self.import_mode = config.get("importConfig","import_mode").lower()
self.export_folder = config.get("exportConfig","export_folder")
self.import_folder = config.get("importConfig","import_folder")
self.export_path = Path(self.export_folder)
self.import_path = Path(self.import_folder)
self.sync_mode = self.loadConfigFlag(config,"importConfig","sync_mode")
self.export_history = self.loadConfigFlag(config,"exportConfig","export_history")
self.export_purge_before_run = self.loadConfigFlag(config,"exportConfig","export_purge_before_run")
self.export_purge_after_zip = self.loadConfigFlag(config,"exportConfig","export_purge_after_zip")
self.append_sddc_id_to_zip = self.loadConfigFlag(config,"exportConfig","append_sddc_id_to_zip")
self.max_export_history_files = int(config.get("exportConfig", "max_export_history_files"))
self.export_type = self.loadConfigFilename(config,"exportConfig","export_type")
self.import_mode_live_warning = self.loadConfigFlag(config,"importConfig","import_mode_live_warning")
self.enable_ipv6 = self.loadConfigFlag(config, 'importConfig', 'enable_ipv6')
self.cluster_rename = self.loadConfigFlag(config, 'importConfig', 'rename_clusters')
# vCenter
self.srcvCenterURL = vCenterConfig.get("vCenterConfig","srcvCenterURL")
self.srcvCenterUsername = vCenterConfig.get("vCenterConfig","srcvCenterUsername")
self.srcvCenterPassword = vCenterConfig.get("vCenterConfig","srcvCenterPassword")
self.srcvCenterDatacenter = vCenterConfig.get("vCenterConfig","srcvCenterDatacenter")
self.srcvCenterSSLVerify = self.loadConfigFlag(vCenterConfig,"vCenterConfig","srcvCenterSSLVerify")
self.destvCenterURL = vCenterConfig.get("vCenterConfig","destvCenterURL")
self.destvCenterUsername = vCenterConfig.get("vCenterConfig","destvCenterUsername")
self.destvCenterPassword = vCenterConfig.get("vCenterConfig","destvCenterPassword")
self.destvCenterDatacenter = vCenterConfig.get("vCenterConfig","destvCenterDatacenter")
self.destvCenterSSLVerify = self.loadConfigFlag(vCenterConfig,"vCenterConfig","destvCenterSSLVerify")
self.export_vcenter_folders = self.loadConfigFlag(config,"exportConfig","export_vcenter_folders")
self.import_vcenter_folders = self.loadConfigFlag(config,"importConfig","import_vcenter_folders")
self.vcenter_folders_filename = self.loadConfigFilename(config,"exportConfig","vcenter_folders_filename")
self.export_vcenter_categories = self.loadConfigFlag(config,"exportConfig","export_vcenter_categories")
self.import_vcenter_categories = self.loadConfigFlag(config,"importConfig","import_vcenter_categories")
self.vcenter_categories_filename = self.loadConfigFilename(config,"exportConfig","vcenter_categories_filename")
self.export_vcenter_tags = self.loadConfigFlag(config,"exportConfig","export_vcenter_tags")
self.import_vcenter_tags = self.loadConfigFlag(config,"importConfig","import_vcenter_tags")
self.vcenter_tags_filename = self.loadConfigFilename(config,"exportConfig","vcenter_tags_filename")
#NSX manager
self.srcNSXmgrURL = vCenterConfig.get("nsxConfig","srcNSXmgrURL")
self.srcNSXmgrUsername = vCenterConfig.get("nsxConfig","srcNSXmgrUsername")
self.srcNSXmgrPassword = vCenterConfig.get("nsxConfig","srcNSXmgrPassword")
self.srcNSXmgrSSLVerify = self.loadConfigFlag(vCenterConfig,"nsxConfig","srcNSXmgrSSLVerify")
# Services
self.services_import = self.loadConfigFlag(config,"importConfig","services_import")
# Groups
self.compute_groups_import = self.loadConfigFlag(config,"importConfig","compute_groups_import")
self.management_groups_import = self.loadConfigFlag(config,"importConfig","management_groups_import")
#CGW
self.cgw_export = self.loadConfigFlag(config,"exportConfig","cgw_export")
self.cgw_export_filename = self.loadConfigFilename(config,"exportConfig","cgw_export_filename")
self.cgw_import = self.loadConfigFlag(config,"importConfig","cgw_import")
self.cgw_import_filename = self.loadConfigFilename(config,"importConfig","cgw_import_filename")
self.cgw_import_exclude_list = self.loadConfigRegex(config,"importConfig","cgw_import_exclude_list",'|')
self.cgw_groups_import_exclude_list = self.loadConfigRegex(config,"importConfig","cgw_groups_import_exclude_list",'|')
#MGW
self.mgw_export = self.loadConfigFlag(config,"exportConfig","mgw_export")
self.mgw_export_filename = self.loadConfigFilename(config,"exportConfig","mgw_export_filename")
self.mgw_import = self.loadConfigFlag(config,"importConfig","mgw_import")
self.mgw_import_filename = self.loadConfigFilename(config,"importConfig","mgw_import_filename")
self.mgw_import_exclude_list = self.loadConfigRegex(config,"importConfig","mgw_import_exclude_list",'|')
self.mgw_groups_import_exclude_list = self.loadConfigRegex(config,"importConfig","mgw_groups_import_exclude_list",'|')
#Multi Tier-1 Compute Gateways
self.mcgw_export = self.loadConfigFlag(config, "exportConfig", "mcgw_export")
self.mcgw_export_filename = self.loadConfigFilename(config, "exportConfig", "mcgw_export_filename")
self.mcgw_static_routes_export = self.loadConfigFlag(config, "exportConfig", "mcgw_static_routes_export")
self.mcgw_static_routes_export_filename = self.loadConfigFilename(config, "exportConfig", "mcgw_static_routes_export_filename")
self.mcgw_fw_export = self.loadConfigFlag(config, "exportConfig", "mcgw_fw_export")
self.mcgw_fw_export_filename = self.loadConfigFilename(config, "exportConfig", "mcgw_fw_export_filename")
self.mcgw_import = self.loadConfigFlag(config, "importConfig", "mcgw_import")
self.mcgw_import_filename = self.loadConfigFilename(config, "importConfig", "mcgw_import_filename")
self.mcgw_static_routes_import = self.loadConfigFlag(config, "importConfig", "mcgw_static_route_import")
self.mcgw_static_route_import_filename = self.loadConfigFilename(config, "importConfig", "mcgw_static_route_import_filename")
self.mcgw_fw_import = self.loadConfigFlag(config, "importConfig", "mcgw_fw_import")
self.mcgw_fw_import_filename = self.loadConfigFilename(config, "importConfig", "mcgw_fw_import_filename")
#Connected VPC Managed Prefix List MOde
self.mpl_export = self.loadConfigFlag(config, 'exportConfig', 'mpl_export')
self.mpl_export_filename = self.loadConfigFilename(config, 'exportConfig', 'mpl_export_filename')
self.mpl_import = self.loadConfigFlag(config, 'importConfig', 'mpl_import')
self.mpl_import_filename = self.loadConfigFilename(config, 'importConfig', 'mpl_import_filename')
self.automate_ram_acceptance = self.loadConfigFlag(config, 'importConfig', 'automate_ram_acceptance')
self.automate_vpc_route_table_programming = self.loadConfigFlag(config, 'importConfig', 'automate_vpc_route_table_programming')
#SDDC Route Aggregation Lists and Route Configurations
self.ral_export = self.loadConfigFlag(config, "exportConfig", "ral_export")
self.ral_export_filename = self.loadConfigFilename(config, "exportConfig", "ral_export_filename")
self.route_config_export = self.loadConfigFlag(config, "exportConfig", "route_config_export")
self.route_config_export_filename = self.loadConfigFilename(config, "exportConfig", "route_config_export_filename")
self.ral_import = self.loadConfigFlag(config, "importConfig", "ral_import")
self.ral_import_filename = self.loadConfigFilename(config, "importConfig", "ral_import_filename")
self.route_config_import = self.loadConfigFlag(config, "importConfig", "route_config_import")
self.route_config_import_filename = self.loadConfigFilename(config, "importConfig", "route_config_import_filename")
#Network segments - CGW
self.network_export = self.loadConfigFlag(config,"exportConfig","network_export")
self.network_export_filename = self.loadConfigFilename(config,"exportConfig","network_export_filename")
self.network_dhcp_static_binding_export = self.loadConfigFilename(config,"exportConfig","network_dhcp_static_binding_export")
self.network_dhcp_static_binding_filename = self.loadConfigFilename(config,"exportConfig","network_dhcp_static_binding_filename")
self.CGWDHCPbindings = []
self.network_import = self.loadConfigFlag(config,"importConfig","network_import")
self.network_import_filename = self.loadConfigFilename(config,"importConfig","network_import_filename")
self.network_dhcp_static_binding_import = self.loadConfigFlag(config,"importConfig","network_dhcp_static_binding_import")
self.network_import_max_networks = int(config.get("importConfig", "network_import_max_networks"))
self.network_import_exclude_list = self.loadConfigRegex(config,"importConfig","network_import_exclude_list",'|')
#Flexible Segments
self.flex_segment_export = self.loadConfigFlag(config, "exportConfig", "flex_segment_export")
self.flex_segment_export_filename = self.loadConfigFilename(config, "exportConfig", "flex_segment_export_filename")
self.flex_segment_disc_prof_export_filename = self.loadConfigFilename(config, 'exportConfig', 'flex_segment_disc_prof_export_filename')
self.flex_segment_import = self.loadConfigFlag(config, "importConfig", "flex_segment_import")
self.flex_segment_import_filename = self.loadConfigFilename(config, "importConfig", "flex_segment_import_filename")
self.flex_segment_import_exclude_list = self.loadConfigRegex(config, "importConfig", "flex_segment_import_exclude_list", '|')
self.flex_segment_disc_prof_import_filename = self.loadConfigFilename(config, 'importConfig', 'flex_segment_disc_prof_import_filename')
#Public IP
self.public_export = self.loadConfigFlag(config,"exportConfig","public_export")
self.public_export_filename = self.loadConfigFilename(config,"exportConfig","public_export_filename")
self.public_import = self.loadConfigFlag(config,"importConfig","public_import")
self.public_import_filename = self.loadConfigFilename(config,"importConfig","public_import_filename")
self.public_ip_old_new_filename = self.loadConfigFilename(config,"importConfig","public_ip_old_new_filename")
#NAT
self.nat_export = self.loadConfigFlag(config,"exportConfig","nat_export")
self.nat_export_filename = self.loadConfigFilename(config,"exportConfig","nat_export_filename")
self.nat_import = self.loadConfigFlag(config,"importConfig","nat_import")
self.nat_import_filename = self.loadConfigFilename(config,"importConfig","nat_import_filename")
#VPN
self.vpn_export = self.loadConfigFlag(config,"exportConfig","vpn_export")
self.vpn_import = self.loadConfigFlag(config,"importConfig","vpn_import")
self.vpn_ike_filename = self.loadConfigFilename(config,"importConfig","vpn_ike_filename")
self.vpn_dpd_filename = self.loadConfigFilename(config,"importConfig","vpn_dpd_filename")
self.vpn_tunnel_filename = self.loadConfigFilename(config,"importConfig","vpn_tunnel_filename")
self.vpn_bgp_filename = self.loadConfigFilename(config,"importConfig","vpn_bgp_filename")
self.vpn_local_bgp_filename = self.loadConfigFilename(config,"importConfig","vpn_local_bgp_filename")
self.vpn_l3_filename = self.loadConfigFilename(config,"importConfig","vpn_l3_filename")
self.vpn_l2_filename = self.loadConfigFilename(config,"importConfig","vpn_l2_filename")
self.vpn_disable_on_import = self.loadConfigFlag(config,"importConfig","vpn_disable_on_import")
self.tier1_vpn_export = self.loadConfigFlag(config, 'exportConfig', 't1_vpn_export')
self.tier1_vpn_export_filename = self.loadConfigFilename(config, 'exportConfig', 't1_vpn_export_filename')
self.tier1_vpn_service_filename = self.loadConfigFilename(config, 'exportConfig', 't1_vpn_service_filename')
self.tier1_vpn_le_filename = self.loadConfigFilename(config, 'exportConfig', 't1_vpn_localendpoint_filename')
#Service Access
self.service_access_export = self.loadConfigFlag(config,"exportConfig","service_access_export")
self.service_access_import = self.loadConfigFlag(config,"importConfig","service_access_import")
self.service_access_filename = self.loadConfigFilename(config,"importConfig","service_access_filename")
#Services
self.services_filename = self.loadConfigFilename(config,"importConfig","services_filename")
#CGW groups
self.cgw_groups_filename = self.loadConfigFilename(config,"importConfig","cgw_groups_filename")
#MGW groups
self.mgw_groups_filename = self.loadConfigFilename(config,"importConfig","mgw_groups_filename")
#AWS
self.aws_s3_export_access_id = self.loadConfigFilename(awsConfig,"awsConfig","aws_s3_export_access_id")
self.aws_s3_export_access_secret = self.loadConfigFilename(awsConfig,"awsConfig","aws_s3_export_access_secret")
self.aws_s3_export_bucket = self.loadConfigFilename(awsConfig,"awsConfig","aws_s3_export_bucket")
self.aws_import_access_key_id = self.loadConfigFilename(awsConfig, 'awsConfig', 'aws_import_access_key_id')
self.aws_import_secret_access_key = self.loadConfigFilename(awsConfig, 'awsConfig', 'aws_import_secret_access_key')
self.aws_import_session_token = self.loadConfigFilename(awsConfig, 'awsConfig', 'aws_import_session_token')
#DFW
self.dfw_export = self.loadConfigFlag(config,"exportConfig","dfw_export")
self.dfw_export_filename = self.loadConfigFilename(config,"exportConfig","dfw_export_filename")
self.dfw_detailed_export_filename = self.loadConfigFilename(config,"exportConfig","dfw_detailed_export_filename")
self.dfw_import = self.loadConfigFlag(config,"importConfig","dfw_import")
self.dfw_import_filename = self.loadConfigFilename(config,"importConfig","dfw_import_filename")
self.dfw_detailed_import_filename = self.loadConfigFilename(config,"importConfig","dfw_detailed_import_filename")
#Advanced Firewall
self.nsx_adv_fw_export = self.loadConfigFlag(config,"exportConfig","nsx_adv_fw_export")
self.nsx_adv_fw_settings_export_filename = self.loadConfigFilename(config,"exportConfig","nsx_adv_fw_settings_export_filename")
self.nsx_adv_fw_sigs_export_filename = self.loadConfigFilename(config, "exportConfig","nsx_adv_fw_sigs_export_filename")
self.nsx_adv_fw_profiles_export_filename = self.loadConfigFilename(config,"exportConfig","nsx_adv_fw_profiles_export_filename")
self.nsx_adv_fw_policies_export_filename = self.loadConfigFilename(config,"exportConfig","nsx_adv_fw_policies_export_filename")
self.nsx_adv_fw_rules_export_filename = self.loadConfigFilename(config,"exportConfig","nsx_adv_fw_rules_export_filename")
self.nsx_adv_fw_import = self.loadConfigFlag(config,"importConfig","nsx_adv_fw_import")
self.nsx_adv_fw_allow_enable = self.loadConfigFlag(config,"importConfig","nsx_adv_fw_allow_enable")
self.nsx_adv_fw_settings_import_filename = self.loadConfigFilename(config,"importConfig","nsx_adv_fw_settings_import_filename")
# self.nsx_adv_fw_sigs_import_filename = self.loadConfigFilename(config, "importConfig","nsx_adv_fw_sigs_import_filename")
self.nsx_adv_fw_profiles_import_filename = self.loadConfigFilename(config,"importConfig","nsx_adv_fw_profiles_import_filename")
self.nsx_adv_fw_policies_import_filename = self.loadConfigFilename(config,"importConfig","nsx_adv_fw_policies_import_filename")
self.nsx_adv_fw_rules_import_filename = self.loadConfigFilename(config,"importConfig","nsx_adv_fw_rules_import_filename")
#NSX Layer 7 Context Profiles
self.nsx_l7_fqdn_export = self.loadConfigFlag(config, 'exportConfig', 'nsx_l7_fqdn_export')
self.nsx_l7_fqdn_filename = self.loadConfigFilename(config, 'exportConfig', 'nsx_l7_fqdn_filename')
self.nsx_l7_context_profile_export = self.loadConfigFlag(config, 'exportConfig', 'nsx_l7_context_profile_export')
self.nsx_l7_context_profile_filename = self.loadConfigFilename(config, 'exportConfig', 'nsx_l7_context_profile_filename')
self.nsx_l7_fqdn_import = self.loadConfigFlag(config, 'importConfig', 'nsx_l7_fqdn_import')
self.nsx_l7_fqdn_import_filename = self.loadConfigFilename(config, 'importConfig', 'nsx_l7_fqdn_import_filename')
self.nsx_l7_context_profile_import = self.loadConfigFlag(config, 'importConfig', 'nsx_l7_context_profile_import')
self.nsx_l7_context_profile_import_filename = self.loadConfigFilename(config, 'importConfig', 'nsx_l7_context_profile_import_filename')
#SDDC Info
self.sddc_info_filename = self.loadConfigFilename(config,"exportConfig","sddc_info_filename")
self.sddc_info_hide_sensitive_data = self.loadConfigFlag(config,"exportConfig","sddc_info_hide_sensitive_data")
#CSP
self.RoleSyncSourceUserEmail = config.get("exportConfig","role_sync_source_user_email")
self.RoleSyncDestUserEmails = config.get("importConfig","role_sync_dest_user_emails").split('|')
def error_handling(self, response):
"""Helper function to properly report API errors"""
code = response.status_code
print(f'API call failed with status code {code}.')
if code == 301:
print(f'Error {code}: "Moved Permanently"')
print("Request must be reissued to a different controller node.")
print(
"The controller node has been replaced by a new node that should be used for this and all future requests.")
elif code == 307:
print(f'Error {code}: "Temporary Redirect"')
print("Request should be reissued to a different controller node.")
print(
"The controller node is requesting the client make further requests against the controller node specified in the Location header. Clients should continue to use the new server until directed otherwise by the new controller node.")
elif code == 400:
print(f'Error {code}: "Bad Request"')
print("Request was improperly formatted or contained an invalid parameter.")
elif code == 401:
print(f'Error {code}: "Unauthorized"')
print("The client has not authenticated.")
print("It's likely your refresh token is out of date or otherwise incorrect.")
elif code == 403:
print(f'Error {code}: "Forbidden"')
print("The client does not have sufficient privileges to execute the request.")
print("The API is likely in read-only mode, or a request was made to modify a read-only property.")
print("It's likely your refresh token does not provide sufficient access.")
elif code == 409:
print(f'Error {code}: "Temporary Redirect"')
print(
"The request can not be performed because it conflicts with configuration on a different entity, or because another client modified the same entity.")
print(
"If the conflict arose because of a conflict with a different entity, modify the conflicting configuration. If the problem is due to a concurrent update, re-fetch the resource, apply the desired update, and reissue the request.")
elif code == 412:
print(f'Error {code}: "Precondition Failed"')
print(
"The request can not be performed because a precondition check failed. Usually, this means that the client sent a PUT or PATCH request with an out-of-date _revision property, probably because some other client has modified the entity since it was retrieved. The client should re-fetch the entry, apply any desired changes, and re-submit the operation.")
elif code == 500:
print(f'Error {code}: "Internal Server Error"')
print(
"An internal error occurred while executing the request. If the problem persists, perform diagnostic system tests, or contact your support representative.")
elif code == 503:
print(f'Error {code}: "Service Unavailable"')
print(
"The request can not be performed because the associated resource could not be reached or is temporarily busy. Please confirm the ORG ID and SDDC ID entries in your config.ini are correct.")
else:
print(f'Error: {code}: Unknown error')
try:
json_response = response.json()
if 'error_message' in json_response:
print(json_response['error_message'])
if 'related_errors' in json_response:
print("Related Errors")
for r in json_response['related_errors']:
print(r['error_message'])
except:
print("No additional information in the error response.")
return None
def purgeJSONfiles(self):
"""Removes the JSON export files before a new export"""
files = glob.glob(self.export_folder + '/*.json')
retval = True
for filePath in files:
try:
os.remove(filePath)
print('Deleted',filePath)
except:
print('Error deleting',filePath)
retval = False
return retval
def zipJSONfiles(self):
"""Creates a zipfile of exported JSON files"""
files = glob.glob(self.export_folder + '/*.json')
curtime = datetime.datetime.now()
#filename example: 2020-12-02_09-57-13_json-export.zip
fname = curtime.strftime("%Y-%m-%d_%H-%M-%S") + '_' + 'json-export.zip'
if self.append_sddc_id_to_zip is True:
fname = self.source_sddc_id + "_" + fname
self.export_zip_name = fname
try:
ZipPath = self.export_folder + '/' + fname
with ZipFile(ZipPath,'w') as zip:
for file in files:
zip.write(file,os.path.basename(file))
return True
except Exception as e:
print('Error writing zipfile: ', str(e))
return False
def unzipJSONfiles(self,sourceZipPath):
"""Unzip a JSON archive"""
try:
if os.path.exists(sourceZipPath) is False:
print(sourceZipPath,'not found.')
return False
# This does not obey the import_folder
with ZipFile(sourceZipPath,mode = 'r') as zip:
zip.extractall(os.path.dirname(sourceZipPath))
return True
except Exception as e:
print('Zipfile extraction error: ', str(e))
return False
def purgeJSONzipfiles(self):
"""Clean up old zipfiles"""
if self.max_export_history_files == -1:
print('Maximum zips configured as unlimited.')
return True
retval = True
files = glob.glob(self.export_folder + '/*.zip')
files.sort(key=os.path.getmtime)
print(len(files), "zipfiles found with a configured maximum of",self.max_export_history_files)
if len(files) > self.max_export_history_files:
num_to_purge = len(files) - self.max_export_history_files
print('Need to purge:',num_to_purge)
for file in files[0:num_to_purge]:
try:
os.remove(file)
print ('Purged', file)
except Exception as e:
retval = False
print('Error purging:', file,str(e))
return retval
def exportOnPremGroups(self):
"""Exports the Groups to a JSON file"""
myURL = (self.srcNSXmgrURL + "/policy/api/v1/infra/domains/default/groups")
response = self.invokeNSXTGET(myURL)
if response is None or response.status_code != 200:
return False
json_response = response.json()
cgw_groups = json_response['results']
fname = self.export_path / self.cgw_groups_filename
with open(fname, 'w') as outfile:
json.dump(cgw_groups, outfile,indent=4)
return True
def exportOnPremServices(self,OnlyUserDefinedServices=False):
"""Exports on-prem services to a JSON file
Args: bool OnlyUserDefinedServices, default True, if you want to ignore predefined system services
"""
myURL = (self.srcNSXmgrURL + "/policy/api/v1/infra/services")
response = self.invokeNSXTGET(myURL)
if response is None or response.status_code != 200:
return False
json_response = response.json()
sddc_services = json_response['results']
if OnlyUserDefinedServices is True:
fname = self.export_path / self.services_filename
with open(fname, 'w+') as outfile:
for service in sddc_services:
if service["_create_user"]!= "admin" and service["_create_user"]!="admin;admin" and service["_create_user"]!="system":
json.dump(service, outfile,indent=4)
else:
fname = self.export_path / self.services_filename
with open(fname, 'w') as outfile:
json.dump(sddc_services, outfile,indent=4)
return True
def exportOnPremDFWRule(self):
"""Exports the on-prem firewall rules to a JSON file"""
myURL = (self.srcNSXmgrURL + "/policy/api/v1/infra/domains/default/security-policies")
response = self.invokeNSXTGET(myURL)
if response is None or response.status_code != 200:
return False
json_response = response.json()
sddc_DFWrules = json_response['results']
sddc_Detailed_DFWrules = {}
for cmap in sddc_DFWrules:
myURL = self.srcNSXmgrURL + "/policy/api/v1/infra/domains/default/security-policies/" + cmap["id"] + "/rules"
response = self.invokeNSXTGET(myURL)
if response is None or response.status_code != 200:
return False
cmapDetails = response.json()
sddc_Detailed_DFWrules[cmap["id"]] = cmapDetails
fname = self.export_path / self.dfw_export_filename
fname_detailed = self.export_path / self.dfw_detailed_export_filename
with open(fname, 'w') as outfile:
json.dump(sddc_DFWrules, outfile,indent=4)
with open(fname_detailed, 'w') as outfile:
json.dump(sddc_Detailed_DFWrules, outfile,indent=4)
return True
def importOnPremServices(self):
self.vmc_auth.check_access_token_expiration()
"""Import all services from a JSON file"""
fname = self.import_path / self.services_filename
try:
with open(fname) as filehandle:
services = json.load(filehandle)
except:
print('Import failed - unable to open',fname)
return
for service in services:
json_data = {}
if service["_create_user"]!="system":
if self.import_mode == "live":
json_data["id"] = service["id"]
json_data["resource_type"]=service["resource_type"]
json_data["display_name"]=service["display_name"]
json_data["service_type"]=service["service_type"]
service_entries = []
for entry in service["service_entries"]:
#print("-------------------------------------------------")
#print("entry")
modified_entry = {}
for k in entry:
#print("-------------------------------------------------")
#print("sub_entry")
#print(k)
if k != "path" and k != "relative_path" and k != "overridden" and k != "_create_time" and k != "_create_user" and k != "_last_modified_time" and k != "_last_modified_user" and k != "_system_owned" and k != "_protection" and k != "_revision":
modified_entry[k] = entry[k]
service_entries.append(modified_entry)
json_data["service_entries"]=service_entries
myHeader = {"Content-Type": "application/json","Accept": "application/json", 'csp-auth-token': self.vmc_auth.access_token }
myURL = self.proxy_url + "/policy/api/v1/infra/services/" + service["id"]
#print(myURL)
#print(json_data)
if self.sync_mode is True:
response = requests.patch(myURL, headers=myHeader, json=json_data)
else:
response = requests.put(myURL, headers=myHeader, json=json_data)
if response.status_code == 200:
result = "SUCCESS"
print('Added {}'.format(json_data['display_name']))
else:
result = "FAIL"
print( f'API Call Status {response.status_code}, text:{response.text}')
else:
print("TEST MODE - Service",service["display_name"],"would have been imported.")
def importOnPremGroup(self):
"""Import all CGW groups from a JSON file"""
self.vmc_auth.check_access_token_expiration()
fname = self.import_path / self.cgw_groups_filename
try:
with open(fname) as filehandle:
groups = json.load(filehandle)
except:
print('Import failed - unable to open',fname)
return False
payload = {}
for group in groups:
skip_vm_expression = False
skip_group = False
for e in self.cgw_groups_import_exclude_list:
m = re.match(e,group["display_name"])
if m:
print(group["display_name"],'skipped - matches exclusion regex', e)
skip_group = True
break
if skip_group is True:
continue
payload["id"]=group["id"]
payload["resource_type"]=group["resource_type"]
payload["display_name"]=group["display_name"]
if self.import_mode == "live":
myHeader = {"Content-Type": "application/json","Accept": "application/json", 'csp-auth-token': self.vmc_auth.access_token }
myURL = self.proxy_url + "/policy/api/v1/infra/domains/cgw/groups/" + group["id"]
if "expression" in group:
group_expression = group["expression"]
for item in group_expression:
if item["resource_type"] == "ExternalIDExpression":
skip_vm_expression = True
print(f'CGW Group {group["display_name"]} cannot be imported as it relies on VM external ID.')
break
else:
continue
if skip_vm_expression == False:
payload["expression"]=group["expression"]
json_data = json.dumps(payload)
if self.sync_mode is True:
creategrpresp = requests.patch(myURL,headers=myHeader,data=json_data)
else:
creategrpresp = requests.put(myURL,headers=myHeader,data=json_data)
print("CGW Group " + payload["display_name"] + " has been imported.")
else:
continue
else:
print("TEST MODE - CGW Group " + payload["display_name"] + " would have been imported.")
payload = {}
return True
def importOnPremDFWRule(self):
"""Import all DFW Rules from a JSON file"""
self.vmc_auth.check_access_token_expiration()
fname = self.import_path / self.dfw_import_filename
fname_detailed = self.import_path / self.dfw_detailed_import_filename
try:
with open(fname) as filehandle:
cmaps = json.load(filehandle)
except:
print('Import failed - unable to open',fname)
return False
try:
with open(fname_detailed) as filehandle:
cmapd = json.load(filehandle)
except:
print('Import failed - unable to open',fname_detailed)
return False
for cmap in cmaps:
if cmap["id"]!="default-layer3-section" and cmap["id"]!="default-layer2-section":
payload = {}
payload["resource_type"] = cmap["resource_type"]
payload["id"] = cmap["id"]
payload["display_name"] = cmap["display_name"]
payload["category"] = cmap["category"]
payload["sequence_number"] = cmap["sequence_number"]
payload["stateful"] = cmap["stateful"]
if self.import_mode == 'live':
myHeader = {"Content-Type": "application/json","Accept": "application/json", 'csp-auth-token': self.vmc_auth.access_token }
myURL = self.proxy_url_short + "/policy/api/v1/infra/domains/cgw/security-policies/" + cmap["id"]
json_data = json.dumps(payload)
if self.sync_mode is True:
response = requests.patch(myURL,headers=myHeader,data=json_data)
else:
response = requests.put(myURL,headers=myHeader,data=json_data)
self.lastJSONResponse = f'API Call Status {response.status_code}, text:{response.text}'
payload = {}
cmap_id = cmap["id"]
commEnts = cmapd[cmap_id]["results"]
for commEnt in commEnts:
payload["id"] = commEnt["id"]
payload["display_name"] = commEnt["display_name"]
payload["resource_type"] = commEnt["resource_type"]
payload["source_groups"] = commEnt["source_groups"]
payload["destination_groups"] = commEnt["destination_groups"]
payload['source_groups'] = [group.replace('/infra/domains/default/groups', '/infra/domains/cgw/groups') for group in payload['source_groups']]
payload['destination_groups'] = [group.replace('/infra/domains/default/groups', '/infra/domains/cgw/groups') for group in payload['destination_groups']]
payload["destination_groups"]
if "scope" in commEnt:
payload["scope"] = commEnt["scope"]
payload["action"] = commEnt["action"]
payload["services"] = commEnt["services"]
payload["sequence_number"] = commEnt["sequence_number"]
payload["logged"] = commEnt["logged"]
payload["disabled"] = commEnt["disabled"]
if self.import_mode == 'live':
myURL = self.proxy_url + "/policy/api/v1/infra/domains/cgw/security-policies/" + cmap["id"] + "/rules/" + commEnt["id"]
myHeader = {"Content-Type": "application/json","Accept": "application/json", 'csp-auth-token': self.vmc_auth.access_token }
json_data = json.dumps(payload)
if self.sync_mode is True:
response = requests.patch(myURL,headers=myHeader,data=json_data)
else:
response = requests.put(myURL,headers=myHeader,data=json_data)
if response.status_code == 200:
print("DFW rule " + commEnt["display_name"] + " has been imported.")
else:
self.lastJSONResponse = f'API Call Status {response.status_code}, text:{response.text}'
print(f'API Call Status {response.status_code}, text:{response.text}')
else:
print("TEST MODE - DFW rule " + commEnt["display_name"] + " would have been imported.")
return True
def exportSDDCCGWnetworks(self):
"""Exports the CGW network segments to a JSON file"""
myURL = (self.proxy_url + "/policy/api/v1/infra/tier-1s/cgw/segments")
response = self.invokeVMCGET(myURL)
if response is None or response.status_code != 200:
return False
json_response = response.json()
cgw_networks = json_response['results']
fname = self.export_path / self.network_export_filename
with open(fname, 'w') as outfile:
json.dump(cgw_networks, outfile,indent=4)
if self.network_dhcp_static_binding_export:
self.CGWDHCPbindings = []
for network in cgw_networks:
retval = self.getSDDCCGWDHCPBindings(network['id'])
fname = self.export_path / self.network_dhcp_static_binding_filename
with open(fname, 'w') as outfile:
json.dump(self.CGWDHCPbindings, outfile, indent=4)
return True
def getSDDCCGWDHCPBindings( self, segment_id: str):
"""Appends any DHCP static bindings for segment_id to the class variable CGWDHCPbindings"""
myURL = (self.proxy_url + f'/policy/api/v1/infra/tier-1s/cgw/segments/{segment_id}/dhcp-static-binding-configs')
#print(myURL)
response = self.invokeVMCGET(myURL)
if response is None or response.status_code != 200:
return False
json_response = response.json()
#print(json_response)
if json_response['result_count'] > 0:
dhcp_static_bindings = json_response['results']
self.CGWDHCPbindings.append(dhcp_static_bindings)
#print(self.CGWDHCPbindings)
else:
return False
def export_flexible_segments(self):
"""Exports the flexible segments to a JSON file"""
my_url = f'{self.proxy_url}/policy/api/v1/infra/segments'
response = self.invokeCSPGET(my_url)
json_response = response.json()
flex_segments = json_response['results']
fname = self.export_path / self.flex_segment_export_filename
with open (fname, 'w') as outfile:
json.dump(flex_segments, outfile, indent=4)
return True
def export_flexible_segment_disc_bindings(self):
"""Exports the MAC and IP Discovery binding maps for each flexible segment to JSON"""
flex_seg_bind = {}
flex_seg_url = f'{self.proxy_url}/policy/api/v1/infra/segments'
flex_seg_resp = self.invokeCSPGET(flex_seg_url)
flex_seg_json = flex_seg_resp.json()
flex_seg_json = flex_seg_json['results']
flex_seg_id = []
for f in flex_seg_json:
flex_seg_name = f['id']
flex_seg_id.append(flex_seg_name)
for x in flex_seg_id:
my_url = f'{self.proxy_url}/policy/api/v1/infra/segments/{x}/segment-discovery-profile-binding-maps'
response = self.invokeCSPGET(my_url)
json_response = response.json()
disc_bind_map = json_response['results']
flex_seg_bind[x] = disc_bind_map
fname = self.export_path / self.flex_segment_disc_prof_export_filename
with open (fname, 'w') as outfile:
json.dump(flex_seg_bind, outfile, indent=4)
return True
def exportSDDCMGWRule(self):
"""Exports the MGW firewall rules to a JSON file"""
myURL = (self.proxy_url + "/policy/api/v1/infra/domains/mgw/gateway-policies/default/rules")
response = self.invokeVMCGET(myURL)
if response is None or response.status_code != 200:
return False
json_response = response.json()
sddc_MGWrules = json_response['results']
fname = self.export_path / self.mgw_export_filename
with open(fname, 'w') as outfile:
json.dump(sddc_MGWrules, outfile,indent=4)
return True
def exportSDDCCGWRule(self):
"""Exports the CGW firewall rules to a JSON file"""
myURL = (self.proxy_url + "/policy/api/v1/infra/domains/cgw/gateway-policies/default/rules")
response = self.invokeVMCGET(myURL)
if response is None or response.status_code != 200:
return False
json_response = response.json()
sddc_CGWrules = json_response['results']
fname = self.export_path / self.cgw_export_filename
with open(fname, 'w') as outfile:
json.dump(sddc_CGWrules, outfile,indent=4)
return True
def exportSDDCMGWGroups(self):
"""Exports MGW firewall groups to a JSON file"""
myURL = (self.proxy_url + "/policy/api/v1/infra/domains/mgw/groups")
response = self.invokeVMCGET(myURL)
if response is None or response.status_code != 200:
return False
json_response = response.json()
mgw_groups = json_response['results']
fname = self.export_path / self.mgw_groups_filename
with open(fname, 'w') as outfile:
json.dump(mgw_groups, outfile,indent=4)
return True
def export_mcgw_config(self):
"""Exports Multi-T1 CGW configuration to a JSON file"""
my_url = f'{self.proxy_url}/policy/api/v1/search?query=resource_type:Tier1'
response = self.invokeCSPGET(my_url)
if response is None or response.status_code != 200:
return False
json_response = response.json()
#print(json.dumps(json_response, indent=2))
search_results = json_response['results']
mcgw_list = []
for i in search_results:
if i['id'] == 'mgw':
pass
elif i['id'] == 'cgw':
pass
else:
mcgw_list.append(i['id'])
mcgw_json = {}
for x in mcgw_list:
my_url = f'{self.proxy_url}/policy/api/v1/infra/tier-1s/{x}'
response = self.invokeCSPGET(my_url)
if response is None or response.status_code != 200:
return False
json_response = response.json()
mcgw_json[x] = json_response
fname = self.export_path / self.mcgw_export_filename
with open(fname, 'w') as outfile:
json.dump(mcgw_json, outfile, indent=4)
return True
def export_mcgw_static_routes(self):
"""Exports any static routes configured on a multi-T1 CGW to a JSON file"""
my_url = f'{self.proxy_url}/policy/api/v1/search?query=resource_type:Tier1'
response = self.invokeCSPGET(my_url)
if response is None or response.status_code != 200:
return False
json_response = response.json()
search_results = json_response['results']
mcgw_list = []
for i in search_results:
if i['id'] == 'mgw':
pass
elif i['id'] == 'cgw':
pass
else:
mcgw_list.append(i['id'])
mcgw_staticroutes_json = {}
for x in mcgw_list:
my_url = f'{self.proxy_url}/policy/api/v1/infra/tier-1s/{x}/static-routes'
response = self.invokeCSPGET(my_url)
if response is None or response.status_code != 200:
return False
json_response = response.json()
mcgw_staticroutes_json[x] = json_response
fname = self.export_path / self.mcgw_static_routes_export_filename
with open(fname, 'w') as outfile:
json.dump(mcgw_staticroutes_json, outfile, indent=4)
return True
def export_mcgw_fw(self):
"""Exports all North/South firewall policies"""
my_url = f'{self.proxy_url}/policy/api/v1/search?query=resource_type:GatewayPolicy'
response = self.invokeCSPGET(my_url)
if response is None or response.status_code != 200:
return False
json_response = response.json()
search_results = json_response['results']
mcgw_policy_list = []
for i in search_results:
if i['id'] == 'default':
pass
elif i['parent_path'] == '/infra/domains/default':
pass
else:
mcgw_policy_list.append(i['id'])
mcgw_fw_policy_json = {}
for x in mcgw_policy_list:
# print(json.dumps(x, indent=2))
my_url = f'{self.proxy_url}/policy/api/v1/infra/domains/cgw/gateway-policies/{x}'
response = self.invokeCSPGET(my_url)
if response is None or response.status_code != 200:
return False
json_response = response.json()
mcgw_fw_policy_json[x] = json_response
fname = self.export_path / self.mcgw_fw_export_filename
with open(fname, 'w') as outfile:
json.dump(mcgw_fw_policy_json, outfile, indent=4)
return True
def export_mpl(self):
"""Exports Connected VPC Managed Prefix List"""
my_url = f'{self.proxy_url}/cloud-service/api/v1/infra/linked-vpcs'
response = self.invokeCSPGET(my_url)
if response is None or response.status_code != 200:
self.error_handling(response)
return False
json_response = response.json()
mpl_response = json_response['results']
fname = self.export_path / self.mpl_export_filename
with open(fname, 'w') as outfile:
json.dump(mpl_response, outfile, indent=4)
return True
def export_advanced_firewall(self):
"""Exports NSX Advanced Firewall settings, profiles, policies and rules"""
successval = True
retval = self.export_nsx_adv_fw_settings()
if retval is False:
successval = False
print('NSX Advanced Firewall settings export failure: ', self.lastJSONResponse)
else:
print('NSX Advanced Firewall settings exported.')
retval = self.export_nsx_adv_fw_exclusions()
if retval is False:
successval = False
print('NSX Advanced Firewall exclusion export failure: ', self.lastJSONResponse)
elif retval is None:
print("No exclusions to export.")
else:
print('NSX Advanced Firewall exclusions exported.')
retval = self.export_ids_profiles()
if retval is False:
successval = False
print('NSX Advanced Firewall profiles export failure: ', self.lastJSONResponse)
else:
print('NSX Advanced Firewall profiles exported.')
retval = self.export_ids_policies()
if retval[0] is False:
successval = False
print('NSX Advanced Firewall policies export failure: ', self.lastJSONResponse)
else:
print('NSX Advanced Firewall policies exported.')
pol_count = retval[1]
pol_list = retval[2]
rule_set = []
if pol_count == 0:
print("There are no policies and therefore no rules to export - skipping NSX Adv FW rules.")
return successval
else:
for policy in pol_list:
retval = self.export_ids_rules(policy)
if retval[0] is False:
successval = False
print('NSX Advanced Firewall rules export failure: ', self.lastJSONResponse)
else:
rule_set.append(retval[1])
print(f'NSX Advanced Firewall rules exported for policy {policy}.')
fname = self.export_path / f'{self.nsx_adv_fw_rules_export_filename}'
with open(fname, 'w') as outfile:
json.dump(rule_set, outfile,indent=4)
return successval
def export_nsx_adv_fw_settings(self):
my_url = f'{self.proxy_url_short}/policy/api/v1/infra/settings/firewall/security/intrusion-services'
response = self.invokeCSPGET(my_url)
if response is None or response.status_code != 200:
return False
json_response = response.json()
fname = self.export_path / self.nsx_adv_fw_settings_export_filename
with open(fname, 'w') as outfile:
json.dump(json_response, outfile,indent=4)
return True
def export_nsx_adv_fw_exclusions(self):
my_url = f'{self.proxy_url_short}/policy/api/v1/infra/settings/firewall/security/intrusion-services/global-signatures'
response = self.invokeCSPGET(my_url)
if response is None or response.status_code != 200:
return False
json_response = response.json()
if json_response['results']:
nsxaf_sigs = json_response['results']
fname = self.export_path / self.nsx_adv_fw_sigs_export_filename
with open(fname, 'w') as outfile:
json.dump(nsxaf_sigs, outfile,indent=4)
return True
else:
return None
def export_ids_profiles(self):
my_url = f'{self.proxy_url_short}/policy/api/v1/infra/settings/firewall/security/intrusion-services/profiles'