nettoolkit 0.0.3__zip

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (16) hide show
  1. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/__init__.py +49 -0
  2. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/__pycache__/__init__.cpython-38.pyc +0 -0
  3. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/__pycache__/addressing.cpython-38.pyc +0 -0
  4. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/__pycache__/gpl.cpython-38.pyc +0 -0
  5. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/__pycache__/hierarchy.cpython-38.pyc +0 -0
  6. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/__pycache__/hierarchy_rules.cpython-38.pyc +0 -0
  7. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/__pycache__/jset.cpython-38.pyc +0 -0
  8. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/addressing.py +920 -0
  9. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/gpl.py +1207 -0
  10. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/hierarchy.py +558 -0
  11. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/hierarchy_rules.py +229 -0
  12. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit/jset.py +109 -0
  13. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit-0.0.3-py3.8.egg-info/PKG-INFO +41 -0
  14. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit-0.0.3-py3.8.egg-info/SOURCES.txt +12 -0
  15. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit-0.0.3-py3.8.egg-info/dependency_links.txt +1 -0
  16. Users/ALI/AppData/Local/Programs/Python/Python38-32/Lib/site-packages/nettoolkit-0.0.3-py3.8.egg-info/top_level.txt +1 -0
@@ -0,0 +1,558 @@
1
+ # -----------------------------------------------------------------------------
2
+ # IMPORTS
3
+ # -----------------------------------------------------------------------------
4
+ from collections import OrderedDict
5
+
6
+ from .hierarchy_rules import *
7
+
8
+ # Enable only if Max Recursion depth reach.
9
+ # import sys
10
+ # sys.setrecursionlimit(10**5)
11
+
12
+
13
+ def mysplit(line, by=" "):
14
+ """
15
+ split line by (default space), also retain the strings like descriptions as it is.
16
+
17
+ Args:
18
+ line (str): string line
19
+ by (character, optional): Split by option. Defaults to " ".
20
+
21
+ Returns:
22
+ list: split line and return list
23
+ """
24
+ spl = line.split(by)
25
+ for item in description_strings:
26
+ if item in spl:
27
+ s1 = spl[:spl.index(item)+1]
28
+ s2 = " ".join(spl[spl.index(item)+1:])
29
+ s1.append(s2)
30
+ return s1
31
+ return spl
32
+
33
+
34
+ def li_li_words(in_str):
35
+ """
36
+ converts multiline string in to list of list of words.
37
+
38
+ Args:
39
+ in_str (str): Multiline string
40
+
41
+ Returns:
42
+ list: list of list of words.
43
+ """
44
+ return [[w for w in mysplit(line[4:])] for line in in_str.split('\n')]
45
+
46
+
47
+ def section_dict(in_list, word, full_review=False):
48
+ """
49
+ create section dectionary from given input list for the selected word.
50
+
51
+ Args:
52
+ in_list (list, str): Input list or string
53
+ word (str): selected word for which list to be search up on and generate dictionary
54
+ full_review (bool, optional): go thru full list if set to true, else only check first match only. Defaults to False.
55
+
56
+ Raises:
57
+ NotImplementedError: Unmatched input type for input.
58
+
59
+ Returns:
60
+ dict: dictionary with key equal input word and value as list of words from matched suffixes.
61
+ """
62
+ section_config_dict = OrderedDict()
63
+ section_config_dict[word] = []
64
+ if isinstance(in_list, str):
65
+ in_list = li_li_words(in_list)
66
+ elif isinstance(in_list, (list, tuple)):
67
+ pass
68
+ else:
69
+ raise NotImplementedError
70
+ for line in in_list:
71
+ section_config_list = []
72
+ add_to = False
73
+ for i, w in enumerate(line):
74
+ wordCheck = i == 0
75
+ if wordCheck and w == word:
76
+ add_to = True
77
+ continue
78
+ elif wordCheck and w != word:
79
+ if not full_review: break
80
+ if add_to:
81
+ section_config_list.append(w)
82
+ if add_to:
83
+ section_config_dict[word].append(section_config_list)
84
+ else:
85
+ if not full_review: break
86
+ return section_config_dict
87
+
88
+
89
+ def zero_items(in_list):
90
+ """
91
+ Return all Zero (0) indexed Items from list of lists
92
+
93
+ Args:
94
+ in_list (list): input list of lists
95
+
96
+ Returns:
97
+ list: all 0-index items from list of lists
98
+ """
99
+ _zi = []
100
+ for item_zero in in_list:
101
+ if item_zero[0] not in _zi: _zi.append(item_zero[0])
102
+ return _zi
103
+
104
+
105
+ def related_list(in_list, word):
106
+ """
107
+ filter input list for the given word in index-0 position
108
+
109
+ Args:
110
+ in_list (list): input list of list
111
+ word (str): word to be check in index-0 position.
112
+
113
+ Returns:
114
+ list: filtered output list
115
+ """
116
+ section_config_list = []
117
+ for line in in_list:
118
+ add_to = line[0] == word
119
+ if add_to: section_config_list.append(line)
120
+ return section_config_list
121
+
122
+
123
+ def recursive_item_lookup(lili_words):
124
+ """
125
+ create and yields dictionary/list from provided list of list of words.
126
+
127
+ Args:
128
+ lili_words (list): input list of list of words
129
+
130
+ Yields:
131
+ dict: yields dictionary item/value pairs
132
+ """
133
+ for ezi in zero_items(lili_words):
134
+ nv = related_list(lili_words, ezi)
135
+ ns_dic = section_dict(nv, ezi)
136
+ yield ns_dic
137
+
138
+
139
+ def excluded(dic, members, member_key):
140
+ """Checks for matching key from provided dictionary (dic) in to members dictionary's member_key,
141
+ returns True if found any.
142
+
143
+ Args:
144
+ dic ([type]): input dictionary for which keys to be searched in to members dictinary members
145
+ members ([type]): members dicationary to be looked in to.
146
+ member_key (str): member key to be looked in to members dictionary
147
+
148
+ Returns:
149
+ bool: True if any excluded member found, None Else
150
+ """
151
+ if member_key in members:
152
+ for k in dic.keys():
153
+ if k in members[member_key]:
154
+ return True
155
+
156
+
157
+ def included(dic, members, member_key):
158
+ """Checks for matching key from provided dictionary (dic) in to members dictionary's member_key,
159
+ returns True if found or member_key not found in members dict.
160
+
161
+ Args:
162
+ dic ([type]): input dictionary for which keys to be searched in to members dictinary members
163
+ members ([type]): members dicationary to be looked in to.
164
+ member_key (str): member key to be looked in to members dictionary
165
+
166
+ Returns:
167
+ bool: True if any excluded member found or member_key not in members, False Else
168
+ """
169
+ if member_key in members:
170
+ for k in dic.keys():
171
+ if k in members[member_key]:
172
+ return True
173
+ return False
174
+ else:
175
+ return True
176
+
177
+
178
+ class Section():
179
+ """Configuration Section Creator"""
180
+
181
+ def __init__(self, in_list, ordered=False):
182
+ """Section Object Initializer
183
+
184
+ Args:
185
+ in_list (list): list of list
186
+ ordered (bool, optional): Section Dictionary to be ordered or unordered. Defaults to False.
187
+ """
188
+ self.lst = in_list
189
+ self.dic = OrderedDict()
190
+ if not ordered: self.dic = {}
191
+ self.add(ordered)
192
+
193
+ def add(self, ordered):
194
+ """add the key value to self.dic
195
+ go thru recursive lookup for dictionary tree
196
+
197
+ Args:
198
+ ordered (bool): dictionary to be ordered or not
199
+ """
200
+ try:
201
+ for dic in recursive_item_lookup(self.lst):
202
+ if isinstance(dic, OrderedDict):
203
+ for k, v in dic.items():
204
+ s = Section(v, ordered=ordered)
205
+ self.dic[k] = s.dic
206
+
207
+ except: pass
208
+
209
+
210
+ class Convert():
211
+ """Converts Dicationary to Hierarchical config string"""
212
+
213
+ def __init__(self,
214
+ dic,
215
+ tabs,
216
+ is_tailed=True,
217
+ is_grouped=False,
218
+ is_distributed=False,
219
+ is_straight=False,
220
+ is_straight_anyway=False,
221
+ parent_prefix = '',
222
+ test=False
223
+ ):
224
+ self.dic = dic
225
+ self.tabs = tabs
226
+ self.is_tailed = is_tailed
227
+ self.is_grouped = is_grouped
228
+ self.is_distributed = is_distributed
229
+ self.is_straight = is_straight
230
+ self.is_straight_anyway = is_straight_anyway
231
+ self.parent_prefix = parent_prefix
232
+ self.test = test
233
+ self.s = ''
234
+ self.tab = ' '
235
+ self.front_tabs = self.tabs
236
+ self.convert
237
+
238
+ def __str__(self): return self.s
239
+
240
+ @property
241
+ def front_tabs(self): return self._front_tabs
242
+
243
+ @front_tabs.setter
244
+ def front_tabs(self, tabs): self._front_tabs = f'{self.tab*tabs}'
245
+
246
+ def add_to_str(self, s): self.s += s
247
+
248
+ def update_front_tabs(self, n):
249
+ self.tabs += n
250
+ self.front_tabs = self.tabs
251
+
252
+ def update_prefix(self, k):
253
+ if self.parent_prefix:
254
+ self.prefix = self.front_tabs + self.parent_prefix + " " + k
255
+ else:
256
+ self.prefix = self.front_tabs + k
257
+ if self.is_tailed or self.is_straight:
258
+ self.prefix = self.parent_prefix + " " + k
259
+ if self.is_distributed:
260
+ pfx_list = self.prefix.split()[-1]
261
+ if pfx_list[-1] != k:
262
+ self.prefix = self.front_tabs + self.parent_prefix + " " + k
263
+
264
+
265
+ @property
266
+ def convert(self):
267
+ """
268
+ start Converting dictionary to config string.
269
+
270
+ Returns:
271
+ None: None
272
+ """
273
+ if len(self.dic) == 0: return None
274
+ for dic_key, dic_value in self.dic.items():
275
+ self.exception(dic_key)
276
+ self.update_prefix(dic_key)
277
+ if isinstance(dic_value, (dict, OrderedDict)):
278
+ self.update_front_tabs(1)
279
+ self.update_prefix(dic_key)
280
+
281
+ if self.logic_terminators(dic_key, dic_value):
282
+ pass
283
+ elif self.logic_groups(dic_key, dic_value):
284
+ pass
285
+
286
+ self.update_front_tabs(-1)
287
+ self.closure
288
+
289
+ # - LOGICS -----------------------------------------------------
290
+
291
+ def exception(self, dic_key):
292
+ if self.tabs == -1:
293
+ if dic_key == 'policy-options':
294
+ # candidates_not_expand_in_anycase.clear()
295
+ candidates_not_expand_if_single.clear()
296
+ candidates_not_expand_if_single.add('from')
297
+ candidates_not_expand_if_single.add('then')
298
+ candidates_not_expand_if_single.add('community')
299
+ elif dic_key =='firewall':
300
+ # candidates_not_expand_in_anycase.clear()
301
+ candidates_not_expand_if_single.clear()
302
+ candidates_not_expand_if_single.add('then')
303
+ elif dic_key =='class-of-service':
304
+ # candidates_not_expand_in_anycase.clear()
305
+ candidates_not_expand_if_single.clear()
306
+ candidates_not_expand_if_single.add('class')
307
+ else:
308
+ candidates_not_expand_if_single.clear()
309
+ # candidates_not_expand_in_anycase.clear()
310
+
311
+ def logic_terminators(self, dic_key, dic_value):
312
+ """line terminators selector logic
313
+
314
+ Args:
315
+ dic_key (str): string key to be pass on to selector logic
316
+ dic_value (dic): dictionary for the key to be pass on to selector logic
317
+
318
+ Returns:
319
+ bool: Returns True if any terminator logic matches found else None
320
+ """
321
+
322
+ # if self.test : print(dic_key)
323
+ # if self.is_straight: print(dic_key)
324
+
325
+ # ex: destination-port [ <"telnet tacacs ldap 636"> ];
326
+ if self.is_grouped:
327
+ self.clubbed_candidate_terminator_lines(dic_key, dic_value)
328
+ return True
329
+
330
+ # ex: <"community add blue;\n community add yellow;\n ....">
331
+ elif self.is_distributed:
332
+ self.distributed_candidate_terminator_lines(dic_key, dic_value)
333
+ return True
334
+
335
+ # Terminators
336
+ elif not dic_value :
337
+ # ex: <"ip-protocol tcp;">
338
+ # ex: <"0.0.0.0/0;">
339
+ self.terminator_line
340
+ return True
341
+
342
+ def logic_groups(self, dic_key, dic_value):
343
+ """section group selector logic
344
+
345
+ Args:
346
+ dic_key (str): string key to be pass on to selector logic
347
+ dic_value (dic): dictionary for the key to be pass on to selector logic
348
+ """
349
+ v = {'cl_from_a_only': {'members': {'2002:61': {}}}, 'cl_prefix_class_access': {'members': {'2002:12': {}}}, 'cl_prefix_class_infra': {'members': {'2002:11': {}}}, 'cl_prefix_class_user': {'members': {'2002:14': {}}}, 'cl_reso_id': {'members': {'163:12786': {}}}, 'cl_rt_blue': {'members': {'target:8:100': {}}}, 'cl_vpn_id_blue': {'members': {'2002:100': {}}}, 'cl_vpn_zone_blue': {'members': {'2002:8': {}}}}
350
+
351
+
352
+ # if self.test : print(dic_key)
353
+ # if self.is_straight: print(dic_key)
354
+ if dic_key == "community" and dic_value == v: self.test = True
355
+ if False: pass
356
+
357
+ elif (len(dic_value) == 1
358
+ and (self.is_straight
359
+ or dic_key in candidates_not_expand_if_single)
360
+ ):
361
+ self.grp_candidate_straight(dic_key, dic_value)
362
+
363
+ # elif (self.is_straight_anyway
364
+ # or dic_key in candidates_not_expand_in_anycase
365
+ # ):
366
+ # self.grp_candidate_straight_anyway(dic_key, dic_value)
367
+
368
+ # ex: <"destination-port"> [ telnet tacacs ldap 636 ];
369
+ elif dic_key in candidates_can_club_members:
370
+ self.grp_candidates_clubbed(dic_key, dic_value)
371
+
372
+ # ex: <"community add blue;\n community add yellow;\n ....">
373
+ elif (dic_key in candidates_distributed_to_multi_lines
374
+ and not excluded(dic_value, candidates_distributed_to_multi_lines_exclude, dic_key)
375
+ and included(dic_value, candidates_distributed_to_multi_lines_include, dic_key)
376
+ ):
377
+ self.grp_candidates_distributed(dic_key, dic_value)
378
+
379
+ # ex: <"term"> al_att_forward_class2_protocol_seq_100 {
380
+ elif (dic_key in candidates_require_suffix
381
+ and not excluded(dic_value, candidates_require_suffix_exclude_members, dic_key)
382
+ and included(dic_value, candidates_require_suffix_include_members, dic_key)
383
+ ):
384
+ self.grp_has_suffix_candidate(dic_key, dic_value)
385
+
386
+ # ex: term <"al_att_forward_class2_protocol_seq_100"> {
387
+ elif self.is_tailed:
388
+ self.grp_suffixes(dic_key, dic_value)
389
+
390
+ # ex: <"ip-source-address"> {
391
+ else:
392
+ self.grp_nested(dic_key, dic_value)
393
+
394
+
395
+ # - CLOSURES -----------------------------------------------------
396
+
397
+ @property
398
+ def closure(self):
399
+ """Append Section closure to string """
400
+ if not self.is_tailed and not self.is_grouped:
401
+ s = self.front_tabs + "}\n"
402
+ self.add_to_str(s)
403
+
404
+
405
+ # - TERMINATORS -----------------------------------------------------
406
+ """
407
+ Args:
408
+ dic_key (str): key/string to be added to config
409
+ dic_value (dict): sub-section config (if any)
410
+
411
+ Returns:
412
+ None: None
413
+ """
414
+
415
+ @property
416
+ def terminator_line(self):
417
+ s = self.prefix + ";\n"
418
+ self.add_to_str(s)
419
+
420
+ def clubbed_candidate_terminator_lines(self, dic_key, dic_value):
421
+ """Clubbed candidates terminator words getting added to string"""
422
+ # if self.test : print(dic_key)
423
+ sObj = Convert(dic_value, self.tabs, is_tailed=True, is_grouped=True)
424
+ s = dic_key + " " + str(sObj)
425
+ self.add_to_str(s)
426
+
427
+ def distributed_candidate_terminator_lines(self, dic_key, dic_value):
428
+ """Distributed terminator candidate words getting added to string"""
429
+ # if self.test : print(dic_key)
430
+ for k, v in dic_value.items():
431
+ s = self.prefix + " " + k + ";\n"
432
+ self.add_to_str(s)
433
+
434
+
435
+ # - GROUPS -----------------------------------------------------
436
+ """
437
+ Args:
438
+ dic_key (str): key/string to be added to config
439
+ dic_value (dict): sub-section config (if any)
440
+
441
+ Returns:
442
+ None: None
443
+ """
444
+
445
+ def grp_candidate_straight(self, dic_key, dic_value):
446
+ # if self.test : print(self.is_straight, dic_key)
447
+ sObj = Convert(dic_value, self.tabs, is_tailed=True, is_straight=self.is_straight)
448
+ # if self.test: print(">", self.prefix, sObj.s)
449
+ s = self.prefix + str(sObj)
450
+ self.add_to_str(s)
451
+
452
+ # def grp_candidate_straight_anyway(self, dic_key, dic_value):
453
+ # s = dic_key
454
+ # for k, v in dic_value.items():
455
+ # # print(k)
456
+ # sObj = Convert(v, self.tabs, is_tailed=True, is_straight_anyway=self.is_straight_anyway, test=self.test)
457
+ # s += "X" + k + "\n"
458
+ # self.add_to_str(self.prefix + s)
459
+
460
+
461
+ def grp_has_suffix_candidate(self, dic_key, dic_value):
462
+ """group config, which has suffix candidate."""
463
+ # if self.test : print(self.is_straight, dic_key)
464
+ if len(dic_value) > 1:
465
+ sObj = Convert(dic_value, self.tabs, is_tailed=True, parent_prefix=self.prefix)
466
+ s = str(sObj)
467
+ else:
468
+ sObj = Convert(dic_value, self.tabs, is_tailed=True)
469
+ s = self.prefix + str(sObj)
470
+ self.add_to_str(s)
471
+
472
+ def grp_suffixes(self, dic_key, dic_value):
473
+ """group config"""
474
+ # if self.test : print(dic_key)
475
+ self.update_front_tabs(-1)
476
+ sObj = Convert(dic_value, self.tabs, is_tailed=False)
477
+ s = self.prefix + " {\n"+ str(sObj)
478
+ self.add_to_str(s)
479
+ self.update_front_tabs(1)
480
+
481
+ def grp_candidates_clubbed(self, dic_key, dic_value):
482
+ """clubbed group config"""
483
+ # if self.test : print(dic_key)
484
+ sObj = Convert(dic_value, self.tabs, is_tailed=True, is_grouped=True)
485
+ if dic_value.get("") and len(dic_value[""]) > 1:
486
+ s = self.prefix + " ["+ str(sObj) + "];\n"
487
+ else:
488
+ s = self.prefix + " "+ str(sObj)[:-1] + ";\n"
489
+ self.add_to_str(s)
490
+
491
+ def grp_candidates_distributed(self, dic_key, dic_value):
492
+ """Distributed group config"""
493
+ # if self.test : print(dic_key)
494
+ pp = self.parent_prefix + dic_key
495
+ sObj = Convert(dic_value, self.tabs-1, is_tailed=True, is_distributed=True, parent_prefix=pp)
496
+ s = str(sObj)
497
+ self.add_to_str(s)
498
+
499
+ # DEFAUT AT END
500
+ def grp_nested(self, dic_key, dic_value):
501
+ """nested group config"""
502
+ # ELSE AFTER ALL grp matches
503
+ # if self.test : print(dic_key)
504
+ sObj = Convert(dic_value, self.tabs, is_tailed=False)
505
+ s = self.prefix + " {\n"+ str(sObj)
506
+ self.add_to_str(s)
507
+
508
+
509
+
510
+ if __name__ == '__main__':
511
+ # set a b low cx c
512
+ # set a b low dx d
513
+ # set a b low ex e
514
+
515
+ l = """set policy-options policy-statement rm_prefix_to_ldp term seq_20 from protocol static
516
+ """
517
+
518
+ #----------------------------------------------------
519
+ # Main Sequences #
520
+ #----------------------------------------------------
521
+ # read set commands file
522
+ with open('g9z-vpb-hpcf1_Jset.cfg', 'r') as f:
523
+ pass
524
+ l = f.read()
525
+
526
+ # Generate Sections Dictionary
527
+ s = Section(li_li_words(l), ordered=False)
528
+ # print(s.dic)
529
+
530
+ # Convert Dictionary to Hierarchical config
531
+ op = Convert(s.dic, -1, is_tailed=False)
532
+
533
+ # write to output file
534
+ with open('normal.txt', 'w') as f:
535
+ f.write(str(op))
536
+
537
+ # print(str(op)[:-5])
538
+ #----------------------------------------------------
539
+
540
+ '''
541
+ Exceptions to be done
542
+
543
+ 3. - NTP servers should not come in brackets.
544
+ server {
545
+ 135.89.176.122;
546
+ 135.89.45.122;
547
+ }
548
+ --> server 135.89.176.122;
549
+ server 135.89.45.122;
550
+
551
+ 4.
552
+ term seqxxx , from / then --> based on entry expand or in single line
553
+
554
+
555
+ 5.
556
+
557
+
558
+ '''