-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathns_extensions.py
1428 lines (1171 loc) · 67.2 KB
/
ns_extensions.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
'''
SPDX-License-Identifier: Apache-2.0
Copyright 2023 Cisco Systems, Inc. and its affiliates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to 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.
See the License for the specific language governing permissions and
limitations under the License.
'''
from idlelib.debugobj_r import remote_object_tree_item
import ns_def, ns_egt_maker, ns_ddx_figure, network_sketcher_cli
from collections import Counter
import tkinter as tk ,tkinter.ttk , openpyxl
import ipaddress, sys, os, re, shutil
import numpy as np
import networkx as nx
class flow_report():
def create_device_flow_table(self,full_filepath_master,device_name):
print('--- create_device_flow_table ---',full_filepath_master,device_name)
## check Flow_Data sheet exists in Master file
input_excel_master = openpyxl.load_workbook(full_filepath_master)
ws_list_master = input_excel_master.sheetnames
input_excel_master.close()
ws_flow_name = 'Flow_Data'
if ws_flow_name in ws_list_master:
master_flow_array = ns_def.convert_excel_to_array(ws_flow_name, full_filepath_master, 3)
master_flow_array = master_flow_array[:-1]
#print(master_flow_array)
target_flow_array = []
for tmp_master_flow_array in master_flow_array:
tmp_routing_path = ''
if tmp_master_flow_array[1][6] != '':
tmp_routing_path = tmp_master_flow_array[1][6]
elif tmp_master_flow_array[1][6] == '' and tmp_master_flow_array[1][6] != ' ':
tmp_routing_path = tmp_master_flow_array[1][7]
if tmp_master_flow_array[1][1] == device_name or tmp_master_flow_array[1][2] == device_name or device_name in tmp_routing_path:
target_flow_array.append([tmp_master_flow_array[1][0],tmp_master_flow_array[1][1],tmp_master_flow_array[1][2],tmp_master_flow_array[1][3],tmp_master_flow_array[1][4],tmp_master_flow_array[1][5],tmp_routing_path])
#print(target_flow_array)
'''
export flow report
'''
excel_maseter_file = full_filepath_master
iDir = os.path.abspath(os.path.dirname(excel_maseter_file))
basename_without_ext = os.path.splitext(os.path.basename(excel_maseter_file))[0]
self.outFileTxt_11_3.delete(0, tkinter.END)
self.outFileTxt_11_3.insert(tk.END, iDir + ns_def.return_os_slash() + '[FLOW_REPORT]' + basename_without_ext.replace('[MASTER]', '') + '.xlsx')
## check file open
ns_def.check_file_open(self.outFileTxt_11_3.get())
# flag exist flow file
flag_flow_table_exist = False
if os.path.isfile(self.outFileTxt_11_3.get()) == True:
#os.remove(self.outFileTxt_11_3.get())
flag_flow_table_exist = True
self.excel_flow_file = self.outFileTxt_11_3.get()
## check Flow_Data sheet exists in Master file
input_excel_master = openpyxl.load_workbook(excel_maseter_file)
ws_list_master = input_excel_master.sheetnames
input_excel_master.close()
'''
MAKE Flows Table List
'''
master_device_table_tuple = {}
flow_list_array = []
egt_maker_width_array = ['5','25', '25','25', '25','15', '20', '25', '40'] # for Network Sketcher Ver 2.0
flow_list_array.append([1, ['<RANGE>', '1','1', '1', '1', '1', '1', '1', '1', '1', '<END>']])
flow_list_array.append([2, ['<HEADER>', 'No','Source Device Name', 'Destination Device Name','Source IP Address', 'Destination IP Address','TCP/UDP/ICMP','Service name(Port)', 'Max. bandwidth(Mbps)', 'Routing path settings', '<END>']])
current_row_num = 3
'''add flow table list'''
#print(self.show_l3_interface)
# Initialize a dictionary to hold devices and their IP addresses
device_ips = {}
# Iterate through the list of interfaces
for tmp_show_l3_interface in self.show_l3_interface:
tmp_device_name = tmp_show_l3_interface[0]
tmp_ip_address = tmp_show_l3_interface[3]
# Add the IP address to the corresponding device in the dictionary
if tmp_device_name not in device_ips:
device_ips[tmp_device_name] = []
device_ips[tmp_device_name].append(tmp_ip_address)
for tmp_target_flow_array in target_flow_array:
tmp_target_flow_array = list(map(str, tmp_target_flow_array))
tmp_target_flow_array.insert(0, '')
tmp_target_flow_array.append('<END>')
source_ip_array = device_ips[tmp_target_flow_array[2]]
destination_ip_array = device_ips[tmp_target_flow_array[3]]
str_source_ip = ', '.join(map(str, source_ip_array ))
str_destination_ip = ', '.join(map(str, destination_ip_array))
tmp_target_flow_array.insert(4, str_source_ip)
tmp_target_flow_array.insert(5, str_destination_ip)
flow_list_array.append([current_row_num,tmp_target_flow_array])
current_row_num += 1
#add last <EMD>
flow_list_array.append([current_row_num, ['<END>']])
#print(flow_list_array)
#print(flow_list_array)
### Convert to tuple
master_device_table_tuple = ns_def.convert_array_to_tuple(flow_list_array)
'''
Create temp input data file
'''
# List of characters not allowed in Excel worksheet names
forbidden_chars = [':', '\\', '/', '?', '*', '[', ']']
# Remove forbidden characters using a list comprehension
cleaned_device_name = ''.join(char for char in device_name if char not in forbidden_chars)
### Create the flow table excel file or add sheet
self.worksheet_name = cleaned_device_name
if flag_flow_table_exist == False:
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = self.worksheet_name
wb.save(self.excel_flow_file)
else:
wb = openpyxl.load_workbook(self.excel_flow_file)
if self.worksheet_name in wb.sheetnames:
# Remove the existing worksheet
sheet_to_remove = wb[self.worksheet_name]
wb.remove(sheet_to_remove)
wb.create_sheet(title=self.worksheet_name)
wb.save(self.excel_flow_file)
'''
Create [FLOW_REPORT] file
'''
tmp_master_data_array = []
tmp_master_data_array.append([1, [self.worksheet_name]])
#print(tmp_master_data_array)
template_master_data_tuple = {}
template_master_data_tuple = ns_def.convert_array_to_tuple(tmp_master_data_array)
#print('Create --- template_master_data_tuple---')
#print(template_master_data_tuple)
offset_row = 0
offset_column = 0
write_to_section = '_template_'
ns_def.write_excel_meta(template_master_data_tuple, self.excel_flow_file, self.worksheet_name, write_to_section, offset_row, offset_column)
###
input_excel_name = self.excel_flow_file
output_excel_name = self.outFileTxt_11_3.get()
if flag_flow_table_exist == False:
NEW_OR_ADD = 'NEW'
else:
NEW_OR_ADD = 'ADD_OPTION1'
ns_egt_maker.create_excel_gui_tree(input_excel_name,output_excel_name,NEW_OR_ADD, egt_maker_width_array)
'''
Add FLOW_List table from meta
'''
# Write normal tuple to excel
tmp_ws_name = '_tmp_'
master_excel_meta = master_device_table_tuple
ppt_meta_file = output_excel_name
excel_file_path = ppt_meta_file
worksheet_name = tmp_ws_name
section_write_to = '<<N/A>>'
offset_row = 0
offset_column = 0
ns_def.create_excel_sheet(ppt_meta_file, tmp_ws_name)
ns_def.write_excel_meta(master_excel_meta, excel_file_path, worksheet_name, section_write_to, offset_row, offset_column)
#print(output_excel_name)
self.input_tree_excel = openpyxl.load_workbook(output_excel_name)
worksheet_name = cleaned_device_name
start_row = 1
start_column = 0
custom_table_name = ppt_meta_file
self.input_tree_excel = ns_egt_maker.insert_custom_excel_table(self.input_tree_excel, worksheet_name, start_row, start_column, custom_table_name)
self.input_tree_excel.save(output_excel_name)
# Remove _tmp_ sheet from excel master self.worksheet_name
ns_def.remove_excel_sheet(ppt_meta_file, tmp_ws_name)
class flow():
def add_routing_path_to_flow(self,full_filepath_master,flow_list_array):
print('--- Routing path calculation ---')
argv_array = ['show', 'l3_broadcast_domain']
l3_broadcast_array = network_sketcher_cli.ns_cli_run.cli_show(self, full_filepath_master, argv_array)
#print(l3_broadcast_array)
G = nx.Graph()
# Add nodes and edges to the graph
for domain_info in l3_broadcast_array:
broadcast_domain, device_interfaces = domain_info
devices = [dev[0] for dev in device_interfaces]
# Connect all devices in the broadcast domain (full graph)
for i in range(len(devices)):
for j in range(i + 1, len(devices)):
G.add_edge(devices[i], devices[j])
for row in flow_list_array[2:]:
data = row[1]
source = data[1]
target = data[2]
path = flow.get_shortest_path(G, source, target)
#print(path)
if 'is not in G' in path:
continue
if len(path) >= 2:
path = path[1:-1]
path2 = ', '.join([f"'{p}'" for p in path])
if path2 == '':
path2 = ' '
data[7] = path2
#print(flow_list_array)
return (flow_list_array)
def get_shortest_path(G,source, target):
try:
path = nx.shortest_path(G, source=source, target=target)
#print(source,target,path, G)
return path
except nx.NetworkXNoPath:
return f"The Path from {source} to {target} could not be found."
except nx.NodeNotFound as e:
return str(e)
def append_flows_to_diagram(self,variable3_7_y_1,variable3_7_y_2,variable3_7_y_3): #add at ver 2.4.3
print('--- append_flows_to_diagram ---')
#print(variable3_7_y_1.get(), variable3_7_y_2.get(), variable3_7_y_3.get())
#print(self.pptx_full_filepath)
#print(self.full_filepath)
ws_flow_name = 'Flow_Data'
excel_maseter_file = self.full_filepath
master_flow_array = ns_def.convert_excel_to_array(ws_flow_name, excel_maseter_file, 3)
# Exclude the last element (['<<END_MARK>>'])
filtered_master_flow = master_flow_array[:-1]
#print(filtered_master_flow)
# Exclude invalid lines
filterd2_master_flow = []
for element in filtered_master_flow:
sublist = element[1] # Take the sublist
# Check if the second or third elements are not empty
if sublist[1] and sublist[2]:
filterd2_master_flow.append(sublist) # Append the sublist without the first number
#print(filterd2_master_flow)
# Filter lines by the target
filtered_target_flow = []
for element in filterd2_master_flow:
# Check if the criteria are met
if (element[1] == variable3_7_y_1.get() or variable3_7_y_1.get() == 'Any') and \
(element[2] == variable3_7_y_2.get() or variable3_7_y_2.get() == 'Any') and \
(element[4] == variable3_7_y_3.get() or variable3_7_y_3.get() == 'Any'):
filtered_target_flow.append(element)
#print(filtered_target_flow)
'''read the pptx file and shapes data'''
self.shape_name_grid_array = []
from pptx import Presentation
from pptx.util import Inches
prs = Presentation(self.pptx_full_filepath)
for shape in prs.slides[0].shapes:
if shape.has_text_frame:
if hasattr(shape, "adjustments"):
try:
if shape.adjustments[0] not in [0.99445, 0.50444, 0.30045, 0.00046, 0.15005, 0.00057, 0.2007] and shape.text.strip() != '': #exclude not (device or wp) shape. 0.0001 device, 0.0008 L3 instance device , 0.2002 way point, 0.2007 l3 instance in device
#print(shape.text.strip(), shape.adjustments[0] , shape.left, shape.top, shape.width, shape.height)
self.shape_name_grid_array.append([shape.text.strip(), shape.left, shape.top, shape.width, shape.height])
except IndexError:
pass
#print(self.shape_name_grid_array)
''' deside routes and write flows '''
if os.path.isfile(self.pptx_full_filepath) == True:
self.active_ppt = Presentation(self.pptx_full_filepath)
self.slide = self.active_ppt.slides[0]
for tmp_filtered_target_flow in filtered_target_flow:
# select routing path is auto or static
selected_route_path = []
if tmp_filtered_target_flow[6] == '' and tmp_filtered_target_flow[7] == ' ':
selected_route_path = [tmp_filtered_target_flow[1], tmp_filtered_target_flow[2]]
elif tmp_filtered_target_flow[6] == '' and tmp_filtered_target_flow[7] != ' ':
selected_route_path = [element.strip().strip("'") for element in tmp_filtered_target_flow[7].split(',')]
selected_route_path.insert(0, tmp_filtered_target_flow[1])
selected_route_path.append(tmp_filtered_target_flow[2])
elif tmp_filtered_target_flow[6] != '':
selected_route_path = [element.strip().strip("'") for element in tmp_filtered_target_flow[6].split(',')]
selected_route_path.insert(0, tmp_filtered_target_flow[1])
selected_route_path.append(tmp_filtered_target_flow[2])
#print(tmp_filtered_target_flow,selected_route_path)
''' write line'''
if len(selected_route_path) == 2:
# get source grid value
source_grid = next(
(item for item in self.shape_name_grid_array if item[0] == tmp_filtered_target_flow[1]),
None # Returns None if no match is found.
)
destination_grid = next(
(item for item in self.shape_name_grid_array if item[0] == tmp_filtered_target_flow[2]),
None # Returns None if no match is found.
)
if source_grid == None or destination_grid == None:
continue
#print(source_grid, destination_grid)
line_type = 'FLOW0'
inche_from_connect_x = (source_grid[1] + source_grid[3] * 0.25) / 914400
inche_from_connect_y = (source_grid[2] + source_grid[4] * 0.5) / 914400
inche_to_connect_x = (destination_grid[1] + destination_grid[3] * 0.75) / 914400
inche_to_connect_y = (destination_grid[2] + destination_grid[4] * 0.5) / 914400
ns_ddx_figure.extended.add_line(self,line_type,inche_from_connect_x,inche_from_connect_y,inche_to_connect_x,inche_to_connect_y)
elif len(selected_route_path) >= 3:
#print(selected_route_path)
for i in range(len(selected_route_path) - 1):
pair = [selected_route_path[i], selected_route_path[i + 1]]
#print(pair,i,len(selected_route_path) - 2 )
# get source grid value
source_grid = next(
(item for item in self.shape_name_grid_array if item[0] == pair[0]),
None # Returns None if no match is found.
)
destination_grid = next(
(item for item in self.shape_name_grid_array if item[0] == pair[1]),
None # Returns None if no match is found.
)
if source_grid == None or destination_grid == None:
continue
if i == 0:
line_type = 'FLOW1'
inche_from_connect_x = (source_grid[1] + source_grid[3] * 0.25) / 914400
inche_from_connect_y = (source_grid[2] + source_grid[4] * 0.5) / 914400
inche_to_connect_x = (destination_grid[1] + destination_grid[3] * 0.5) / 914400
inche_to_connect_y = (destination_grid[2] + destination_grid[4] * 0.5) / 914400
ns_ddx_figure.extended.add_line(self, line_type, inche_from_connect_x, inche_from_connect_y,inche_to_connect_x, inche_to_connect_y)
elif i == len(selected_route_path) - 2:
line_type = 'FLOW2'
inche_from_connect_x = (source_grid[1] + source_grid[3] * 0.5) / 914400
inche_from_connect_y = (source_grid[2] + source_grid[4] * 0.5) / 914400
inche_to_connect_x = (destination_grid[1] + destination_grid[3] * 0.75) / 914400
inche_to_connect_y = (destination_grid[2] + destination_grid[4] * 0.5) / 914400
ns_ddx_figure.extended.add_line(self, line_type, inche_from_connect_x, inche_from_connect_y,inche_to_connect_x, inche_to_connect_y)
else:
line_type = 'FLOW3'
inche_from_connect_x = (source_grid[1] + source_grid[3] * 0.5) / 914400
inche_from_connect_y = (source_grid[2] + source_grid[4] * 0.5) / 914400
inche_to_connect_x = (destination_grid[1] + destination_grid[3] * 0.5) / 914400
inche_to_connect_y = (destination_grid[2] + destination_grid[4] * 0.5) / 914400
ns_ddx_figure.extended.add_line(self, line_type, inche_from_connect_x, inche_from_connect_y,inche_to_connect_x, inche_to_connect_y)
folder = os.path.dirname(self.pptx_full_filepath)
filename = os.path.basename(self.pptx_full_filepath)
modified_filepath = os.path.join(folder, f"Added_flows_{filename}")
self.active_ppt.save(modified_filepath)
#file open
ns_def.messagebox_file_open(modified_filepath)
def get_flow_item_list(self): # add at ver 2.4.3
#print('--- get_flow_item_list ---')
excel_maseter_file = self.inFileTxt_L2_3_1.get()
## check Flow_Data sheet exists in Master file
input_excel_master = openpyxl.load_workbook(excel_maseter_file)
ws_list_master = input_excel_master.sheetnames
input_excel_master.close()
ws_flow_name = 'Flow_Data'
if ws_flow_name in ws_list_master:
master_flow_array = ns_def.convert_excel_to_array(ws_flow_name, excel_maseter_file, 3)
# Exclude the last element (['<<END_MARK>>'])
filtered_master_flow = master_flow_array[:-1]
# Group elements from the 2nd, 3rd, 4th, and 5th positions into separate lists
category_wise_data = [[] for _ in range(4)] # Prepare 4 category lists
for entry in filtered_master_flow:
data = entry[1] # Extract the second element (list)
for i in range(4): # Process the 2nd, 3rd, 4th, and 5th elements (index 1 to 4)
value = data[i + 1].strip()
if value and value not in category_wise_data[i]: # Add only non-empty, non-duplicate values
category_wise_data[i].append(value)
update_master_flow_array = category_wise_data
return(update_master_flow_array)
else:
print('--- Master file does not have Flow_Data sheet ---')
def export_flow_file(self,dummy):
print('--- export_flow_file ---')
excel_maseter_file = self.inFileTxt_L2_3_1.get()
iDir = os.path.abspath(os.path.dirname(excel_maseter_file))
basename_without_ext = os.path.splitext(os.path.basename(excel_maseter_file))[0]
self.outFileTxt_11_3.delete(0, tkinter.END)
self.outFileTxt_11_3.insert(tk.END, iDir + ns_def.return_os_slash() + '[FLOW]' + basename_without_ext.replace('[MASTER]', '') + '.xlsx')
## check file open
ns_def.check_file_open(self.outFileTxt_11_3.get())
# remove exist flow file
if os.path.isfile(self.outFileTxt_11_3.get()) == True:
os.remove(self.outFileTxt_11_3.get())
self.excel_flow_file = self.outFileTxt_11_3.get()
## check Flow_Data sheet exists in Master file
input_excel_master = openpyxl.load_workbook(excel_maseter_file)
ws_list_master = input_excel_master.sheetnames
input_excel_master.close()
ws_flow_name = 'Flow_Data'
flag_master_has_flow_sheet = False
if ws_flow_name in ws_list_master:
flag_master_has_flow_sheet = True
master_flow_array = []
master_flow_array = ns_def.convert_excel_to_array(ws_flow_name, excel_maseter_file, 3)
if '<<END_MARK>>' in master_flow_array[-1][1]:
master_flow_array = master_flow_array[:-1]
#print(master_flow_array)
'''
MAKE Flows List
'''
master_device_table_tuple = {}
flow_list_array = []
egt_maker_width_array = ['5','25', '25','15', '20', '25', '40', '40'] # for Network Sketcher Ver 2.0
flow_list_array.append([1, ['<RANGE>', '1','1', '1', '1', '1', '1', '1', '1', '<END>']])
flow_list_array.append([2, ['<HEADER>', 'No','Source Device Name', 'Destination Device Name','TCP/UDP/ICMP','Service name(Port)', 'Max. bandwidth(Mbps)', 'Manually rouging path settings', 'Automatic rouging path settings', '<END>']])
current_row_num = 3
all_empty = False
if flag_master_has_flow_sheet == True:
# check last ten column = empty
last_10_elements = [item[1] for item in master_flow_array[-1:]]
all_empty = all(all(element == '' for element in item[1:7]) for item in last_10_elements)
for tmp_master_flow_array in master_flow_array:
for i in range(1, 8):
if tmp_master_flow_array[1][i] == '':
tmp_master_flow_array[1][i] = '<EMPTY>'
print(tmp_master_flow_array[1][7])
flow_list_array.append([current_row_num, ['',str(current_row_num - 2), '>>' + str(tmp_master_flow_array[1][1]), '>>' + str(tmp_master_flow_array[1][2]), '>>' + str(tmp_master_flow_array[1][3]), '>>' + str(tmp_master_flow_array[1][4]), '>>' + str(tmp_master_flow_array[1][5]), '>>' + str(tmp_master_flow_array[1][6]),str(tmp_master_flow_array[1][7]), '<END>']])
current_row_num += 1
if flag_master_has_flow_sheet == True and all_empty == True:
add_column_num = 0
elif flag_master_has_flow_sheet == True and all_empty == False:
add_column_num = 10
else:
add_column_num = 100
current_row_max = add_column_num + current_row_num
for n in range(current_row_num, current_row_max):
flow_list_array.append([n, ['',str(n - 2), '<EMPTY>', '<EMPTY>', '<EMPTY>', '<EMPTY>', '<EMPTY>', '<EMPTY>',' ', '<END>']])
flow_list_array.append([current_row_max, ['<END>']])
#print(flow_list_array)
### Convert to tuple
master_device_table_tuple = ns_def.convert_array_to_tuple(flow_list_array)
'''
Create temp input data file
'''
### Create new data excel file
self.worksheet_name = 'Flow_List'
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = self.worksheet_name
wb.save(self.excel_flow_file)
'''
Create [FLOW] file
'''
tmp_master_data_array = []
tmp_master_data_array.append([1,[self.worksheet_name]])
#tmp_master_data_array.append([2,[self.worksheet_name]])
#print(tmp_master_data_array)
template_master_data_tuple = {}
template_master_data_tuple = ns_def.convert_array_to_tuple(tmp_master_data_array)
#print('Create --- template_master_data_tuple---')
#print(template_master_data_tuple)
offset_row = 0
offset_column = 0
write_to_section = '_template_'
ns_def.write_excel_meta(template_master_data_tuple, self.excel_flow_file, self.worksheet_name, write_to_section, offset_row, offset_column)
###
input_excel_name = self.excel_flow_file
output_excel_name = self.outFileTxt_11_3.get()
NEW_OR_ADD = 'NEW'
ns_egt_maker.create_excel_gui_tree(input_excel_name,output_excel_name,NEW_OR_ADD, egt_maker_width_array)
'''
Add FLOW_List table from meta
'''
# Write normal tuple to excel
tmp_ws_name = '_tmp_'
master_excel_meta = master_device_table_tuple
ppt_meta_file = output_excel_name
excel_file_path = ppt_meta_file
worksheet_name = tmp_ws_name
section_write_to = '<<N/A>>'
offset_row = 0
offset_column = 0
ns_def.create_excel_sheet(ppt_meta_file, tmp_ws_name)
ns_def.write_excel_meta(master_excel_meta, excel_file_path, worksheet_name, section_write_to, offset_row, offset_column)
#print(output_excel_name)
self.input_tree_excel = openpyxl.load_workbook(output_excel_name)
worksheet_name = 'Flow_List'
start_row = 1
start_column = 0
custom_table_name = ppt_meta_file
self.input_tree_excel = ns_egt_maker.insert_custom_excel_table(self.input_tree_excel, worksheet_name, start_row, start_column, custom_table_name)
self.input_tree_excel.save(output_excel_name)
'''
Add Drop list
'''
from openpyxl.worksheet.datavalidation import DataValidation
# Load the Excel file
wb = openpyxl.load_workbook(output_excel_name)
ws = wb['Flow_List'] # Select the worksheet 'Flow_List'
# Create a dropdown list (Enable in-cell dropdown)
dv2 = DataValidation(type="list", formula1='"TCP,UDP,ICMP"', allow_blank=True, showDropDown=False)
dv3 = DataValidation(type="list", formula1='"Any,FTP Data(20),FTP Control(21),SSH(22),Telnet(23),SMTP(25),DNS(53),DHCP Server(67),DHCP Client(68),HTTP(80),NNTP(119),NTP(123),IMAP(143),SNMP(161),SNMP Trap(162),BGP(179),HTTPS(443),SMB(445),SMTPS(465),SMTP(587),IMAPS(993),RDP(3389)"', allow_blank=True, showDropDown=False)
# Apply data validation to cell C3
row = 3
for n in range(row, 103):
column = 4
ws.add_data_validation(dv2)
dv2.add(ws.cell(row=n, column=column))
column = 5
ws.add_data_validation(dv3)
dv3.add(ws.cell(row=n, column=column))
# Save the flow file
output_file = output_excel_name
wb.save(output_file)
print(f"Flow file is saved: {output_file}")
# Remove _tmp_ sheet from excel master
ns_def.remove_excel_sheet(ppt_meta_file, tmp_ws_name)
class ip_report():
def export_ip_report(self,dummy):
print('--- export_ip_report ---')
excel_maseter_file = self.inFileTxt_L2_3_1.get()
iDir = os.path.abspath(os.path.dirname(excel_maseter_file))
# SET IP Address report file patch
basename_without_ext = os.path.splitext(os.path.basename(excel_maseter_file))[0]
self.outFileTxt_11_3.delete(0, tkinter.END)
self.outFileTxt_11_3.insert(tk.END, iDir + ns_def.return_os_slash() + '[IP_REPORT]' + basename_without_ext.replace('[MASTER]', '') + '.xlsx') #change IP_TABLE to IP_REPORT at ver 2.5.1
self.excel_file_path = iDir + ns_def.return_os_slash() + '_template_[IP_REPORT]' + basename_without_ext.replace('[MASTER]', '') + '.xlsx' #change IP_TABLE to IP_REPORT at ver 2.5.1
## check file open
ns_def.check_file_open(self.outFileTxt_11_3.get())
# remove exist ip table file
if os.path.isfile(self.outFileTxt_11_3.get()) == True:
os.remove(self.outFileTxt_11_3.get())
self.excel_file_path = self.outFileTxt_11_3.get()
'''
MAKE IP Address List
'''
master_device_table_tuple = {}
ip_address_list_array = []
egt_maker_width_array = ['20', '20', '20', '20', '25', '15', '20'] # for Network Sketcher Ver 2.0
ip_address_list_array.append([1, ['<RANGE>', '1', '1', '1', '1', '1', '1', '1', '<END>']])
ip_address_list_array.append([2, ['<HEADER>', 'IP Address', 'Mask', 'Network Address', 'Device Name', 'L3 IF Name', 'L3 Instance', 'Area', '<END>']])
current_row_num = 3
kari_ip_address_list_array = []
l3_segment_group_array = ns_def.get_l3_segments(self)
#print(l3_segment_group_array)
tmp_seg_array = []
for tmp_l3_segment_group_array in l3_segment_group_array:
#print(tmp_l3_segment_group_array)
for tmp_tmp_l3_segment_group_array in tmp_l3_segment_group_array:
tmp_seg_array.append([tmp_tmp_l3_segment_group_array[0],tmp_tmp_l3_segment_group_array[4]])
ip_with_subnet = tmp_tmp_l3_segment_group_array[4]
ip_address = '[None]'
subnet_mask = '[None]'
network_address = '[None]'
L3_instance = ' '
if tmp_tmp_l3_segment_group_array[3] != '':
L3_instance = tmp_tmp_l3_segment_group_array[3]
if '/' in str(ip_with_subnet):
network = ipaddress.ip_network(ip_with_subnet, strict=False)
ip_interface = ipaddress.ip_interface(ip_with_subnet)
ip_address = str(ip_interface.ip)
subnet_mask = str(ip_interface.netmask)
ip_address_dummy, prefix_length = ip_with_subnet.split('/')
network_address = str(network.network_address) + str('/') + str(prefix_length)
numeric_sequence = ''.join(f'{int(octet):03}' for octet in ip_address.split('.'))
if ip_address == '[None]':
numeric_sequence = str(255255255255)
kari_ip_address_list_array.append([numeric_sequence,ip_address,subnet_mask,network_address,tmp_tmp_l3_segment_group_array[1],tmp_tmp_l3_segment_group_array[2],L3_instance,tmp_tmp_l3_segment_group_array[0], '<END>'])
# Remove completely duplicate columns at ver 2.2.1(c)
unique_tuples_set = set(tuple(item) for item in kari_ip_address_list_array)
unique_list = [list(item) for item in unique_tuples_set]
unique_array = np.array(unique_list)
sorted_lists = sorted(unique_array, key=lambda x: x[0], reverse=False)
#print(sorted_lists)
for tmp_sorted_lists in sorted_lists:
tmp_sorted_lists[0] = ''
ip_address_list_array.append([current_row_num,tmp_sorted_lists])
current_row_num += 1
ip_address_list_array.append([current_row_num, ['<END>']])
#print(ip_address_list_array)
### Convert to tuple
master_device_table_tuple = ns_def.convert_array_to_tuple(ip_address_list_array)
'''
MAKE Summary
'''
summary_list_master_device_table_tuple = {}
summary_list_array = []
summary_list_array.append([1, ['<RANGE>', '1', '1','<END>']])
summary_list_array.append([2, ['<HEADER>', 'Area', 'Summary(CIDR)', '<END>']])
area_list = ip_report.get_folder_list(self)
current_row_num = 3
#print(tmp_seg_array)
get_folder = ip_report.get_folder_list(self)
#print(get_folder)
for tmp_get_folder in get_folder:
kari_sum_array = []
for tmp_tmp_seg_array in tmp_seg_array:
if tmp_tmp_seg_array[0] == tmp_get_folder and tmp_tmp_seg_array[1] != '':
kari_sum_array.append(tmp_tmp_seg_array[1])
#print(kari_sum_array)
networks = [ipaddress.ip_network(cidr, strict=False) for cidr in kari_sum_array]
# clac summary
summary_address = ipaddress.collapse_addresses(networks)
summary_address_list = [str(network) for network in summary_address]
#print(tmp_get_folder,str(summary_address_list))
first_area_flag = True
for tmp_summary_address_list in summary_address_list:
if first_area_flag == True:
summary_list_array.append([current_row_num, ['', tmp_get_folder, str(tmp_summary_address_list), '<END>']])
current_row_num += 1
first_area_flag = False
else:
summary_list_array.append([current_row_num, ['', '', str(tmp_summary_address_list), '<END>']])
current_row_num += 1
summary_list_array.append([current_row_num, ['<END>']])
#print(summary_list_array)
### Convert to tuple
master_summary_table_tuple = ns_def.convert_array_to_tuple(summary_list_array)
'''
Create temp input data file
'''
### Create new data excel file
self.worksheet_name = 'IP Address_List'
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = self.worksheet_name
wb.save(self.excel_file_path)
'''
Create [IP Address] file
'''
tmp_master_data_array = []
tmp_master_data_array.append([1,['Summary']])
tmp_master_data_array.append([2,[self.worksheet_name]])
#print(tmp_master_data_array)
template_master_data_tuple = {}
template_master_data_tuple = ns_def.convert_array_to_tuple(tmp_master_data_array)
#print('Create --- template_master_data_tuple---')
#print(template_master_data_tuple)
offset_row = 0
offset_column = 0
write_to_section = '_template_'
ns_def.write_excel_meta(template_master_data_tuple, self.excel_file_path, self.worksheet_name, write_to_section, offset_row, offset_column)
###
input_excel_name = self.excel_file_path
output_excel_name = self.outFileTxt_11_3.get()
NEW_OR_ADD = 'NEW'
ns_egt_maker.create_excel_gui_tree(input_excel_name,output_excel_name,NEW_OR_ADD, egt_maker_width_array)
'''
Add IP Address_List table from meta
'''
# Write normal tuple to excel
tmp_ws_name = '_tmp_'
master_excel_meta = master_summary_table_tuple
ppt_meta_file = output_excel_name
excel_file_path = ppt_meta_file
worksheet_name = tmp_ws_name
section_write_to = '<<N/A>>'
offset_row = 0
offset_column = 0
ns_def.create_excel_sheet(ppt_meta_file, tmp_ws_name)
ns_def.write_excel_meta(master_excel_meta, excel_file_path, worksheet_name, section_write_to, offset_row, offset_column)
#print(output_excel_name)
self.input_tree_excel = openpyxl.load_workbook(output_excel_name)
worksheet_name = 'Summary'
start_row = 1
start_column = 0
custom_table_name = ppt_meta_file
self.input_tree_excel = ns_egt_maker.insert_custom_excel_table(self.input_tree_excel, worksheet_name, start_row, start_column, custom_table_name)
self.input_tree_excel.save(output_excel_name)
# Remove _tmp_ sheet from excel master
ns_def.remove_excel_sheet(ppt_meta_file, tmp_ws_name)
'''
Add Summary table from meta
'''
# Write normal tuple to excel
tmp_ws_name = '_tmp_'
master_excel_meta = master_device_table_tuple
ppt_meta_file = output_excel_name
excel_file_path = ppt_meta_file
worksheet_name = tmp_ws_name
section_write_to = '<<N/A>>'
offset_row = 0
offset_column = 0
ns_def.create_excel_sheet(ppt_meta_file, tmp_ws_name)
ns_def.write_excel_meta(master_excel_meta, excel_file_path, worksheet_name, section_write_to, offset_row, offset_column)
#print(output_excel_name)
self.input_tree_excel = openpyxl.load_workbook(output_excel_name)
worksheet_name = 'IP Address_List'
start_row = 1
start_column = 0
custom_table_name = ppt_meta_file
self.input_tree_excel = ns_egt_maker.insert_custom_excel_table(self.input_tree_excel, worksheet_name, start_row, start_column, custom_table_name)
self.input_tree_excel.save(output_excel_name)
# Remove _tmp_ sheet from excel master
ns_def.remove_excel_sheet(ppt_meta_file, tmp_ws_name)
def get_folder_list(self):
#print('--- get_folder_list ---')
#parameter
ws_name = 'Master_Data'
excel_maseter_file = self.inFileTxt_L2_3_1.get()
# GET Folder and wp name List
self.folder_wp_name_array = ns_def.get_folder_wp_array_from_master(ws_name, excel_maseter_file)
#print('---- folder_wp_name_array ----')
#print(self.folder_wp_name_array)
return_array = self.folder_wp_name_array[0]
return_array.sort(reverse=False)
#if len(self.folder_wp_name_array[1]) >= 1:
# return_array.append("_WAN(Way_Point)_")
return return_array
class auto_ip_addressing():
def get_folder_list(self):
#print('--- get_folder_list ---')
#parameter
ws_name = 'Master_Data'
excel_maseter_file = self.inFileTxt_L2_3_1.get()
# GET Folder and wp name List
self.folder_wp_name_array = ns_def.get_folder_wp_array_from_master(ws_name, excel_maseter_file)
#print('---- folder_wp_name_array ----')
#print(self.folder_wp_name_array)
return_array = self.folder_wp_name_array[0]
return_array.sort(reverse=False)
if len(self.folder_wp_name_array[1]) >= 1:
return_array.append("_WAN(Way_Point)_")
return return_array
def get_auto_ip_param(self,target_area_name):
#print('--- get_auto_ip_param ---')
#print(target_area_name)
if target_area_name == "_WAN(Way_Point)_":
target_area_name = 'N/A'
'''get values of Master Data'''
#parameter
ws_name = 'Master_Data'
ws_l2_name = 'Master_Data_L2'
ws_l3_name = 'Master_Data_L3'
excel_maseter_file = self.inFileTxt_L3_3_1.get()
self.result_get_l2_broadcast_domains = ns_def.get_l2_broadcast_domains.run(self,excel_maseter_file) ## 'self.update_l2_table_array, device_l2_boradcast_domain_array, device_l2_directly_l3vport_array, device_l2_other_array, marged_l2_broadcast_group_array'
#print('--- self.update_l2_table_array ---')
#print(self.result_get_l2_broadcast_domains[0])
#print('--- self.device_l2_boradcast_domain_array ---')
#print(self.result_get_l2_broadcast_domains[1])
#self.device_l2_boradcast_domain_array = self.result_get_l2_broadcast_domains[1]
#print('--- device_l2_directly_l3vport_array ---')
#print(self.result_get_l2_broadcast_domains[2])
#self.device_l2_directly_l3vport_array = self.result_get_l2_broadcast_domains[2]
#print('--- device_l2_other_array ---')
#print(self.result_get_l2_broadcast_domains[3])
self.device_l2_other_array = self.result_get_l2_broadcast_domains[3]
#print('--- marged_l2_broadcast_group_array ---')
#print(self.result_get_l2_broadcast_domains[4])
self.marged_l2_broadcast_group_array = self.result_get_l2_broadcast_domains[4]
#print('--- self.target_l2_broadcast_group_array ---')
#print(self.target_l2_broadcast_group_array)
self.l3_table_array = ns_def.convert_master_to_array(ws_l3_name, excel_maseter_file, '<<L3_TABLE>>')
#print('--- self.l3_table_array ---')
#print(self.l3_table_array )
# check ip address exists in target area
flag_no_ipaddress = True
add_l3_table_array = []
for index, tmp_l3_table_array in enumerate(self.l3_table_array):
str(tmp_l3_table_array).replace(' ', '')
if index >= 2:
if tmp_l3_table_array[1][0] == target_area_name:
#print(tmp_l3_table_array[1])
if len(tmp_l3_table_array[1]) == 5:
flag_no_ipaddress = False
if len(tmp_l3_table_array[1]) == 5:
if ',' in str(tmp_l3_table_array[1][4]):
#print('--- tmp_l3_table_array ', str(tmp_l3_table_array))
tmp_tmp_l3_table_array= str(tmp_l3_table_array[1][4]).split(',')
for tmp_add_array in tmp_tmp_l3_table_array:
tmp_tmp_tmp_l3_table_array = tmp_l3_table_array
tmp_tmp_tmp_l3_table_array[1][4] = tmp_add_array
#print('--- tmp_tmp_tmp_l3_table_array ', tmp_tmp_tmp_l3_table_array)
self.l3_table_array.append([tmp_tmp_tmp_l3_table_array[0],[tmp_tmp_tmp_l3_table_array[1][0],tmp_tmp_tmp_l3_table_array[1][1],tmp_tmp_tmp_l3_table_array[1][2],tmp_tmp_tmp_l3_table_array[1][3],tmp_tmp_tmp_l3_table_array[1][4]]])
#print ('flag_no_ipaddress', str(flag_no_ipaddress))
outside_ip_address_list = []
inside_ip_address_list = []
full_ip_address_list = []
for index, tmp_l3_table_array in enumerate(self.l3_table_array):
if index >= 2:
if len(tmp_l3_table_array[1]) == 5 and ',' not in str(tmp_l3_table_array[1][4]):
full_ip_address_list.append(str(tmp_l3_table_array[1][4]).replace(' ', ''))
if tmp_l3_table_array[1][0] != target_area_name:
if len(tmp_l3_table_array[1]) == 5 and ',' not in str(tmp_l3_table_array[1][4]):
# print(tmp_l3_table_array[1][4])
first_octet = int(str(tmp_l3_table_array[1][4]).split('.')[0])
second_octet = int(str(tmp_l3_table_array[1][4]).split('.')[1])
third_octet = int(str(tmp_l3_table_array[1][4]).split('.')[2])
outside_ip_address_list.append(str(first_octet) + '.' + str(second_octet)+ '.' + str(third_octet) + '.0')
else:
if len(tmp_l3_table_array[1]) == 5 and ',' not in str(tmp_l3_table_array[1][4]):
# print(tmp_l3_table_array[1][4])
first_octet = int(str(tmp_l3_table_array[1][4]).split('.')[0])
second_octet = int(str(tmp_l3_table_array[1][4]).split('.')[1])
third_octet = int(str(tmp_l3_table_array[1][4]).split('.')[2])
inside_ip_address_list.append(str(first_octet) + '.' + str(second_octet) + '.' + str(third_octet) + '.0')
if flag_no_ipaddress == True:
current_ip_address_list = outside_ip_address_list
else:
current_ip_address_list = inside_ip_address_list
#print(current_ip_address_list )
if current_ip_address_list != []:
word_counts = Counter(current_ip_address_list)
most_common_word, most_common_count = word_counts.most_common(1)[0]
print(f"--- most_common_word: {most_common_word} (most_common_count: {most_common_count})")
else:
most_common_word = '10.0.0.0'
use_network = ''
'''get starting ip address'''
# set starting ip address
start_ip = ipaddress.IPv4Address(most_common_word)
# count for 192 , 172 , 10
if most_common_word.startswith('192.168.'):
increase_count = 256
elif most_common_word.startswith('172.'):
for i in range(16, 32):
if most_common_word.startswith('172.' + str(i) + '.'):
increase_count = 256 * 16
elif most_common_word.startswith('10.'):
increase_count = 256 * 256
else:
start_ip = ipaddress.IPv4Address('10.0.0.0')
increase_count = 256 * 256
# output start network address(CIDR)
flag_1st_third_octet = True
for _ in range(increase_count):
# Convert IP address to byte array
ip_bytes = start_ip.packed
# Get the third octet and increase by 1
third_octet = ip_bytes[2] + 1
# If the third octet exceeds 255, the second octet is also increased
if third_octet > 255:
second_octet = ip_bytes[1] + 1
third_octet = 0 # Omitted if the second octet exceeds 255
else:
second_octet = ip_bytes[1]
if flag_1st_third_octet == True:
third_octet -= 1
flag_1st_third_octet = False
# Build a new IP address
new_ip_bytes = bytearray(ip_bytes)
new_ip_bytes[1] = second_octet
new_ip_bytes[2] = third_octet