-
Notifications
You must be signed in to change notification settings - Fork 220
/
ciscoconfparse.py
executable file
·2694 lines (2287 loc) · 109 KB
/
ciscoconfparse.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
from collections import MutableSequence, Iterator
from operator import methodcaller, attrgetter
from difflib import SequenceMatcher
import time
import re
import os
from models_cisco import IOSHostnameLine, IOSRouteLine, IOSIntfLine
from models_cisco import IOSAccessLine, IOSIntfGlobal
from models_cisco import IOSAaaLoginAuthenticationLine
from models_cisco import IOSAaaEnableAuthenticationLine
from models_cisco import IOSAaaCommandsAuthorizationLine
from models_cisco import IOSAaaCommandsAccountingLine
from models_cisco import IOSAaaExecAccountingLine
from models_cisco import IOSAaaGroupServerLine
from models_cisco import IOSCfgLine
from models_asa import ASAObjGroupNetwork
from models_asa import ASAObjGroupService
from models_asa import ASAHostnameLine
from models_asa import ASAObjNetwork
from models_asa import ASAObjService
from models_asa import ASAIntfGlobal
from models_asa import ASAIntfLine
from models_asa import ASACfgLine
from models_asa import ASAName
from models_junos import JunosCfgLine
from version import __version__ as __ccpversion__
""" ciscoconfparse.py - Parse, Query, Build, and Modify IOS-style configurations
Copyright (C) 2007-2015 David Michael Pennington
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
If you need to contact the author, you can do so by emailing:
mike [~at~] pennington [/dot\] net
"""
## Docstring props: http://stackoverflow.com/a/1523456/667301
__version__ = __ccpversion__
__email__ = "mike /at\ pennington [dot] net"
__author__ = "David Michael Pennington <{0}>".format(__email__)
__copyright__ = "2007-{0}, {1}".format(time.strftime('%Y'), __author__)
__license__ = "GPLv3"
__status__ = "Production"
class CiscoConfParse(object):
"""Parses Cisco IOS configurations and answers queries about the configs"""
def __init__(self, config="", comment="!", debug=False, factory=False,
linesplit_rgx=r"\r*\n+", ignore_blank_lines=True, syntax='ios'):
"""Initialize CiscoConfParse.
Kwargs:
- config (list or str): A list of configuration statements, or a configuration file path to be parsed
- comment (str): A comment delimiter. This should only be changed when parsing non-Cisco IOS configurations, which do not use a ! as the comment delimiter. ``comment`` defaults to '!'
- debug (bool): ``debug`` defaults to False, and should be kept that way unless you're working on a very tricky config parsing problem. Debug output is not particularly friendly
- factory (bool): ``factory`` defaults to False; if set ``True``, it enables a beta-quality configuration line classifier.
- linesplit_rgx (str): ``linesplit_rgx`` is used when parsing configuration files to find where new configuration lines are. It is best to leave this as the default, unless you're working on a system that uses unusual line terminations (for instance something besides Unix, OSX, or Windows)
- ignore_blank_lines (bool): ``ignore_blank_lines`` defaults to True; when this is set True, ciscoconfparse ignores blank configuration lines. You might want to set ``ignore_blank_lines`` to False if you intentionally use blank lines in your configuration (ref: Github Issue #2), or you are parsing configurations which naturally have blank lines (such as Cisco Nexus configurations).
- syntax (str): ``syntax`` defaults to 'ios'; You can choose from the following values: ios, asa
Attributes:
- comment_delimiter (str): A string containing the comment-delimiter
- ConfigObjs (:class:`~ciscoconfparse.IOSConfigList`) : A custom list, which contains all parsed :class:`~models_cisco.IOSCfgLine` instances.
- all_parents (list) : A list of all parent :class:`~models_cisco.IOSCfgLine` instances.
- last_index (int) : An integer with the last index in ``ConfigObjs``
Returns:
- An instance of a :class:`~ciscoconfparse.CiscoConfParse` object
This example illustrates how to parse a simple Cisco IOS configuration
with :class:`~ciscoconfparse.CiscoConfParse` into a variable called
``parse``. This example also illustrates what the ``ConfigObjs``
and ``ioscfg`` attributes contain.
.. code-block:: python
:emphasize-lines: 5
>>> config = [
... 'logging trap debugging',
... 'logging 172.28.26.15',
... ]
>>> parse = CiscoConfParse(config)
>>> parse
<CiscoConfParse: 2 lines / syntax: ios / comment delimiter: '!' / factory: False>
>>> parse.ConfigObjs
<IOSConfigList, comment='!', conf=[<IOSCfgLine # 0 'logging trap debugging'>, <IOSCfgLine # 1 'logging 172.28.26.15'>]>
>>> parse.ioscfg
['logging trap debugging', 'logging 172.28.26.15']
>>>
"""
# all IOSCfgLine object instances...
self.comment_delimiter = comment
self.factory = factory
self.ConfigObjs = None
self.syntax = syntax
if isinstance(config, list) or isinstance(config, Iterator):
if syntax=='ios':
# we already have a list object, simply call the parser
self.ConfigObjs = IOSConfigList(data=config,
comment_delimiter=comment,
debug=debug,
factory=factory,
ignore_blank_lines=ignore_blank_lines,
syntax='ios',
CiscoConfParse=self)
elif syntax=='asa':
# we already have a list object, simply call the parser
self.ConfigObjs = ASAConfigList(data=config,
comment_delimiter=comment,
debug=debug,
factory=factory,
ignore_blank_lines=ignore_blank_lines,
syntax='asa',
CiscoConfParse=self)
elif syntax=='junos':
## FIXME I am shamelessly abusing the IOSConfigList for now...
# we already have a list object, simply call the parser
config = self.convert_braces_to_ios(config)
self.ConfigObjs = IOSConfigList(data=config,
comment_delimiter=comment,
debug=debug,
factory=factory,
ignore_blank_lines=ignore_blank_lines,
syntax='junos',
CiscoConfParse=self)
else:
raise ValueError("FATAL: '{}' is an unknown syntax".format(syntax))
elif isinstance(config, str):
# Try opening as a file
try:
if syntax=='ios':
# string - assume a filename... open file, split and parse
f = open(config, mode="rU")
text = f.read()
rgx = re.compile(linesplit_rgx)
self.ConfigObjs = IOSConfigList(rgx.split(text),
comment_delimiter=comment,
debug=debug,
factory=factory,
ignore_blank_lines=ignore_blank_lines,
syntax='ios',
CiscoConfParse=self)
elif syntax=='asa':
# string - assume a filename... open file, split and parse
f = open(config, mode="rU")
text = f.read()
rgx = re.compile(linesplit_rgx)
self.ConfigObjs = ASAConfigList(rgx.split(text),
comment_delimiter=comment,
debug=debug,
factory=factory,
ignore_blank_lines=ignore_blank_lines,
syntax='asa',
CiscoConfParse=self)
elif syntax=='junos':
# string - assume a filename... open file, split and parse
f = open(config, mode="rU")
text = f.read()
rgx = re.compile(linesplit_rgx)
config = self.convert_braces_to_ios(rgx.split(text))
## FIXME I am shamelessly abusing the IOSConfigList for now...
self.ConfigObjs = IOSConfigList(config,
comment_delimiter=comment,
debug=debug,
factory=factory,
ignore_blank_lines=ignore_blank_lines,
syntax='junos',
CiscoConfParse=self)
else:
raise ValueError("FATAL: '{}' is an unknown syntax".format(syntax))
except IOError:
print("[FATAL] CiscoConfParse could not open '%s'" % config)
raise RuntimeError
else:
raise RuntimeError("[FATAL] CiscoConfParse() received" +
" an invalid argument\n")
self.ConfigObjs.CiscoConfParse = self
def __repr__(self):
return "<CiscoConfParse: %s lines / syntax: %s / comment delimiter: '%s' / factory: %s>" % (len(self.ConfigObjs), self.syntax, self.comment_delimiter, self.factory)
@property
def ioscfg(self):
"""A list containing all text configuration statements"""
## I keep this here to emulate the legacy ciscoconfparse behavior
return list(map(attrgetter('text'), self.ConfigObjs))
@property
def objs(self):
"""An alias to the ``ConfigObjs`` attribute"""
return self.ConfigObjs
def atomic(self):
"""Call :func:`~ciscoconfparse.CiscoConfParse.atomic` to manually fix
up ``ConfigObjs`` relationships
after modifying a parsed configuration. This method is slow; try to
batch calls to :func:`~ciscoconfparse.CiscoConfParse.atomic()` if
possible.
.. warning::
If you modify a configuration after parsing it with
:class:`~ciscoconfparse.CiscoConfParse`, you *must* call
:func:`~ciscoconfparse.CiscoConfParse.commit` or
:func:`~ciscoconfparse.CiscoConfParse.atomic` before searching
the configuration again with methods such as
:func:`~ciscoconfparse.CiscoConfParse.find_objects` or
:func:`~ciscoconfparse.CiscoConfParse.find_lines`. Failure to
call :func:`~ciscoconfparse.CiscoConfParse.commit` or
:func:`~ciscoconfparse.CiscoConfParse.atomic` on config
modifications could lead to unexpected search results.
"""
self.ConfigObjs._bootstrap_from_text()
def commit(self):
"""Alias for calling the :func:`~ciscoconfparse.CiscoConfParse.atomic`
method. This method is slow; try to batch calls to
:func:`~ciscoconfparse.CiscoConfParse.commit()` if possible.
.. warning::
If you modify a configuration after parsing it with
:class:`~ciscoconfparse.CiscoConfParse`, you *must* call
:func:`~ciscoconfparse.CiscoConfParse.commit` or
:func:`~ciscoconfparse.CiscoConfParse.atomic` before searching
the configuration again with methods such as
:func:`~ciscoconfparse.CiscoConfParse.find_objects` or
:func:`~ciscoconfparse.CiscoConfParse.find_lines`. Failure to
call :func:`~ciscoconfparse.CiscoConfParse.commit` or
:func:`~ciscoconfparse.CiscoConfParse.atomic` on config
modifications could lead to unexpected search results.
"""
self.atomic()
def convert_braces_to_ios(self, input_list, stop_width=4):
## Note to self, I made this regex fairly junos-specific...
LINE_RE = re.compile(r'^\s*([^\{\}].*)*\s*([\{\}\;])(\s\#.+)*$')
def line_level(input):
level_offset = 0
mm = LINE_RE.search(input)
if not (mm is None):
line = mm.group(1) or ''
term_char = mm.group(2).strip()
if term_char=='{':
level_offset = 1
elif term_char=='}':
level_offset = -1
return line, level_offset
elif input.strip()=='':
## pass blank lines back
return input, 0
else:
raise ValueError("Could not parse: '{0}'".format(input))
lines = list()
offset = 0
STOP_WIDTH = stop_width
for tmp in input_list:
line, line_offset = line_level(tmp.strip())
if line:
lines.append(" "*STOP_WIDTH*offset+line)
offset += line_offset
return lines
def find_interface_objects(self, intfspec, exactmatch=True):
"""Find all :class:`~models_cisco.IOSCfgLine` objects whose text
is an abbreviation for ``intfspec`` and return the
:class:`~models_cisco.IOSIntfLine` objects in a python list.
.. note::
The configuration *must* be parsed with ``factory=True`` to
use this method
Args:
- intfspec (str): A string which is the abbreviation (or full name) of the interface
Kwargs:
- exactmatch (bool): Defaults to True; when True, this option requires ``intfspec`` match the whole interface name and number.
Returns:
- list. A list of matching :class:`~ciscoconfparse.IOSIntfLine` objects
.. code-block:: python
:emphasize-lines: 12,15
>>> config = [
... '!',
... 'interface Serial1/0',
... ' ip address 1.1.1.1 255.255.255.252',
... '!',
... 'interface Serial1/1',
... ' ip address 1.1.1.5 255.255.255.252',
... '!',
... ]
>>> parse = CiscoConfParse(config, factory=True)
>>>
>>> parse.find_interface_objects('Se 1/0')
[<IOSIntfLine # 1 'Serial1/0' info: '1.1.1.1/30'>]
>>>
"""
if not (self.factory is True):
raise ValueError("FATAL: find_interface_objects() must be called with 'factory=True'")
retval = list()
if self.syntax=='ios':
if exactmatch:
for obj in self.find_objects('^interface'):
if intfspec.lower() in obj.abbvs:
retval.append(obj)
break # Only break if exactmatch is True
else:
raise NotImplementedError
## TODO: implement ASAConfigLine.abbvs and others
else:
raise NotImplementedError
return retval
def find_objects(self, linespec, exactmatch=False, ignore_ws=False):
"""Find all :class:`~models_cisco.IOSCfgLine` objects whose text
matches ``linespec`` and return the :class:`~models_cisco.IOSCfgLine`
objects in a python list.
:func:`~ciscoconfparse.CiscoConfParse.find_objects` is similar to
:func:`~ciscoconfparse.CiscoConfParse.find_lines`; however, the former
returns a list of :class:`~models_cisco.IOSCfgLine` objects, while the
latter returns a list of text configuration statements. Going
forward, I strongly encourage people to start using
:func:`~ciscoconfparse.CiscoConfParse.find_objects` instead of
:func:`~ciscoconfparse.CiscoConfParse.find_lines`.
Args:
- linespec (str): A string or python regular expression, which should be matched
Kwargs:
- exactmatch (bool): Defaults to False. When set True, this option requires ``linespec`` match the whole configuration line, instead of a portion of the configuration line.
- ignore_ws (bool): boolean that controls whether whitespace is ignored. Default is False.
Returns:
- list. A list of matching :class:`~ciscoconfparse.IOSCfgLine` objects
This example illustrates the difference between
:func:`~ciscoconfparse.CiscoConfParse.find_objects` and
:func:`~ciscoconfparse.CiscoConfParse.find_lines`.
.. code-block:: python
:emphasize-lines: 12,15
>>> config = [
... '!',
... 'interface Serial1/0',
... ' ip address 1.1.1.1 255.255.255.252',
... '!',
... 'interface Serial1/1',
... ' ip address 1.1.1.5 255.255.255.252',
... '!',
... ]
>>> parse = CiscoConfParse(config)
>>>
>>> parse.find_objects(r'^interface')
[<IOSCfgLine # 1 'interface Serial1/0'>, <IOSCfgLine # 4 'interface Serial1/1'>]
>>>
>>> parse.find_lines(r'^interface')
['interface Serial1/0', 'interface Serial1/1']
>>>
"""
if ignore_ws:
linespec = self._build_space_tolerant_regex(linespec)
return self._find_line_OBJ(linespec, exactmatch)
def find_lines(self, linespec, exactmatch=False, ignore_ws=False):
"""This method is the equivalent of a simple configuration grep
(Case-sensitive).
Args:
- linespec (str): Text regular expression for the line to be matched
Kwargs:
- exactmatch (bool): Defaults to False. When set True, this option requires ``linespec`` match the whole configuration line, instead of a portion of the configuration line.
- ignore_ws (bool): boolean that controls whether whitespace is ignored. Default is False.
Returns:
- list. A list of matching configuration lines
"""
if ignore_ws:
linespec = self._build_space_tolerant_regex(linespec)
if (exactmatch is False):
# Return the lines in self.ioscfg, which match linespec
return list(filter(re.compile(linespec).search, self.ioscfg))
else:
# Return the lines in self.ioscfg, which match (exactly) linespec
return list(filter(re.compile("^%s$" % linespec).search, self.ioscfg))
def find_children(self, linespec, exactmatch=False, ignore_ws=False):
"""Returns the parents matching the linespec, and their immediate
children. This method is different than :meth:`find_all_children`,
because :meth:`find_all_children` finds children of children.
:meth:`find_children` only finds immediate children.
Args:
- linespec (str): Text regular expression for the line to be matched
Kwargs:
- exactmatch (bool): boolean that controls whether partial matches are valid
- ignore_ws (bool): boolean that controls whether whitespace is ignored
Returns:
- list. A list of matching configuration lines
Suppose you are interested in finding all immediate children of the
`archive` statements in the following configuration...
.. code::
username ddclient password 7 107D3D232342041E3A
archive
log config
logging enable
hidekeys
path ftp://ns.foo.com//tftpboot/Foo-archive
!
Using the config above, we expect to find the following config lines...
.. code::
archive
log config
path ftp://ns.foo.com//tftpboot/Foo-archive
We would accomplish this by querying `find_children('^archive')`...
.. code-block:: python
:emphasize-lines: 11
>>> from ciscoconfparse import CiscoConfParse
>>> config = ['username ddclient password 7 107D3D232342041E3A',
... 'archive',
... ' log config',
... ' logging enable',
... ' hidekeys',
... ' path ftp://ns.foo.com//tftpboot/Foo-archive',
... '!',
... ]
>>> p = CiscoConfParse(config)
>>> p.find_children('^archive')
['archive', ' log config', ' path ftp://ns.foo.com//tftpboot/Foo-archive']
>>>
"""
if ignore_ws:
linespec = self._build_space_tolerant_regex(linespec)
if (exactmatch is False):
parentobjs = self._find_line_OBJ(linespec)
else:
parentobjs = self._find_line_OBJ("^%s$" % linespec)
allobjs = set([])
for parent in parentobjs:
if (parent.has_children is True):
allobjs.update(set(parent.children))
allobjs.add(parent)
return list(map(attrgetter('text'), sorted(allobjs)))
def find_all_children(self, linespec, exactmatch=False, ignore_ws=False):
"""Returns the parents matching the linespec, and all their children.
This method is different than :meth:`find_children`, because
:meth:`find_all_children` finds children of children.
:meth:`find_children` only finds immediate children.
Args:
- linespec (str): Text regular expression for the line to be matched
Kwargs:
- exactmatch (bool): boolean that controls whether partial matches are valid
- ignore_ws (bool): boolean that controls whether whitespace is ignored
Returns:
- list. A list of matching configuration lines
Suppose you are interested in finding all `archive` statements in
the following configuration...
.. code::
username ddclient password 7 107D3D232342041E3A
archive
log config
logging enable
hidekeys
path ftp://ns.foo.com//tftpboot/Foo-archive
!
Using the config above, we expect to find the following config lines...
.. code::
archive
log config
logging enable
hidekeys
path ftp://ns.foo.com//tftpboot/Foo-archive
We would accomplish this by querying `find_all_children('^archive')`...
.. code-block:: python
:emphasize-lines: 11
>>> from ciscoconfparse import CiscoConfParse
>>> config = ['username ddclient password 7 107D3D232342041E3A',
... 'archive',
... ' log config',
... ' logging enable',
... ' hidekeys',
... ' path ftp://ns.foo.com//tftpboot/Foo-archive',
... '!',
... ]
>>> p = CiscoConfParse(config)
>>> p.find_all_children('^archive')
['archive', ' log config', ' logging enable', ' hidekeys', ' path ftp://ns.foo.com//tftpboot/Foo-archive']
>>>
"""
if ignore_ws:
linespec = self._build_space_tolerant_regex(linespec)
if (exactmatch is False):
parentobjs = self._find_line_OBJ(linespec)
else:
parentobjs = self._find_line_OBJ("^%s$" % linespec)
allobjs = set([])
for parent in parentobjs:
allobjs.add(parent)
allobjs.update(set(parent.all_children))
return list(map(attrgetter('text'), sorted(allobjs)))
def find_blocks(self, linespec, exactmatch=False, ignore_ws=False):
"""Find all siblings matching the linespec, then find all parents of
those siblings. Return a list of config lines sorted by line number,
lowest first. Note: any children of the siblings should NOT be
returned.
Args:
- linespec (str): Text regular expression for the line to be matched
Kwargs:
- exactmatch (bool): boolean that controls whether partial matches are valid
- ignore_ws (bool): boolean that controls whether whitespace is ignored
Returns:
- list. A list of matching configuration lines
This example finds `bandwidth percent` statements in following config,
the siblings of those `bandwidth percent` statements, as well
as the parent configuration statements required to access them.
.. code::
!
policy-map EXTERNAL_CBWFQ
class IP_PREC_HIGH
priority percent 10
police cir percent 10
conform-action transmit
exceed-action drop
class IP_PREC_MEDIUM
bandwidth percent 50
queue-limit 100
class class-default
bandwidth percent 40
queue-limit 100
policy-map SHAPE_HEIR
class ALL
shape average 630000
service-policy EXTERNAL_CBWFQ
!
The following config lines should be returned:
.. code::
policy-map EXTERNAL_CBWFQ
class IP_PREC_MEDIUM
bandwidth percent 50
queue-limit 100
class class-default
bandwidth percent 40
queue-limit 100
We do this by quering `find_blocks('bandwidth percent')`...
.. code-block:: python
:emphasize-lines: 22,25
>>> from ciscoconfparse import CiscoConfParse
>>> config = ['!',
... 'policy-map EXTERNAL_CBWFQ',
... ' class IP_PREC_HIGH',
... ' priority percent 10',
... ' police cir percent 10',
... ' conform-action transmit',
... ' exceed-action drop',
... ' class IP_PREC_MEDIUM',
... ' bandwidth percent 50',
... ' queue-limit 100',
... ' class class-default',
... ' bandwidth percent 40',
... ' queue-limit 100',
... 'policy-map SHAPE_HEIR',
... ' class ALL',
... ' shape average 630000',
... ' service-policy EXTERNAL_CBWFQ',
... '!',
... ]
>>> p = CiscoConfParse(config)
>>> p.find_blocks('bandwidth percent')
['policy-map EXTERNAL_CBWFQ', ' class IP_PREC_MEDIUM', ' bandwidth percent 50', ' queue-limit 100', ' class class-default', ' bandwidth percent 40', ' queue-limit 100']
>>>
>>> p.find_blocks(' class class-default')
['policy-map EXTERNAL_CBWFQ', ' class IP_PREC_HIGH', ' class IP_PREC_MEDIUM', ' class class-default']
>>>
"""
tmp = set([])
if ignore_ws:
linespec = self._build_space_tolerant_regex(linespec)
# Find line objects maching the spec
if (exactmatch is False):
objs = self._find_line_OBJ(linespec)
else:
objs = self._find_line_OBJ("^%s$" % linespec)
for obj in objs:
tmp.add(obj)
# Find the siblings of this line
sib_objs = self._find_sibling_OBJ(obj)
for sib_obj in sib_objs:
tmp.add(sib_obj)
# Find the parents for everything
pobjs = set([])
for lineobject in tmp:
for pobj in lineobject.all_parents:
pobjs.add(pobj)
tmp.update(pobjs)
return list(map(attrgetter('text'), sorted(tmp)))
def find_objects_w_child(self, parentspec, childspec, ignore_ws=False):
"""Return a list of parent :class:`~models_cisco.IOSCfgLine` objects,
which matched the ``parentspec`` and whose children match ``childspec``.
Only the parent :class:`~models_cisco.IOSCfgLine` objects will be
returned.
Args:
- parentspec (str): Text regular expression for the :class:`~models_cisco.IOSCfgLine` object to be matched; this must match the parent's line
- childspec (str): Text regular expression for the line to be matched; this must match the child's line
Kwargs:
- ignore_ws (bool): boolean that controls whether whitespace is ignored
Returns:
- list. A list of matching parent :class:`~models_cisco.IOSCfgLine` objects
This example uses :func:`~ciscoconfparse.find_objects_w_child()` to
find all ports that are members of access vlan 300 in following
config...
.. code::
!
interface FastEthernet0/1
switchport access vlan 532
spanning-tree vlan 532 cost 3
!
interface FastEthernet0/2
switchport access vlan 300
spanning-tree portfast
!
interface FastEthernet0/2
duplex full
speed 100
switchport access vlan 300
spanning-tree portfast
!
The following interfaces should be returned:
.. code::
interface FastEthernet0/2
interface FastEthernet0/3
We do this by quering `find_objects_w_child()`; we set our
parent as `^interface` and set the child as `switchport access
vlan 300`.
.. code-block:: python
:emphasize-lines: 18
>>> config = ['!',
... 'interface FastEthernet0/1',
... ' switchport access vlan 532',
... ' spanning-tree vlan 532 cost 3',
... '!',
... 'interface FastEthernet0/2',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... '!',
... 'interface FastEthernet0/3',
... ' duplex full',
... ' speed 100',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... '!',
... ]
>>> p = CiscoConfParse(config)
>>> p.find_objects_w_child('^interface',
... 'switchport access vlan 300')
...
[<IOSCfgLine # 5 'interface FastEthernet0/2'>, <IOSCfgLine # 9 'interface FastEthernet0/3'>]
>>>
"""
if ignore_ws:
parentspec = self._build_space_tolerant_regex(parentspec)
childspec = self._build_space_tolerant_regex(childspec)
return list(filter(lambda x: x.re_search_children(childspec),
self.find_objects(parentspec)))
def find_parents_w_child(self, parentspec, childspec, ignore_ws=False):
"""Parse through all children matching childspec, and return a list of
parents that matched the parentspec. Only the parent lines will be
returned.
Args:
- parentspec (str): Text regular expression for the line to be matched; this must match the parent's line
- childspec (str): Text regular expression for the line to be matched; this must match the child's line
Kwargs:
- ignore_ws (bool): boolean that controls whether whitespace is ignored
Returns:
- list. A list of matching parent configuration lines
This example finds all ports that are members of access vlan 300
in following config...
.. code::
!
interface FastEthernet0/1
switchport access vlan 532
spanning-tree vlan 532 cost 3
!
interface FastEthernet0/2
switchport access vlan 300
spanning-tree portfast
!
interface FastEthernet0/2
duplex full
speed 100
switchport access vlan 300
spanning-tree portfast
!
The following interfaces should be returned:
.. code::
interface FastEthernet0/2
interface FastEthernet0/3
We do this by quering `find_parents_w_child()`; we set our
parent as `^interface` and set the child as
`switchport access vlan 300`.
.. code-block:: python
:emphasize-lines: 18
>>> config = ['!',
... 'interface FastEthernet0/1',
... ' switchport access vlan 532',
... ' spanning-tree vlan 532 cost 3',
... '!',
... 'interface FastEthernet0/2',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... '!',
... 'interface FastEthernet0/3',
... ' duplex full',
... ' speed 100',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... '!',
... ]
>>> p = CiscoConfParse(config)
>>> p.find_parents_w_child('^interface', 'switchport access vlan 300')
['interface FastEthernet0/2', 'interface FastEthernet0/3']
>>>
"""
tmp = self.find_objects_w_child(parentspec, childspec,
ignore_ws=ignore_ws)
return list(map(attrgetter('text'), tmp))
def find_objects_wo_child(self, parentspec, childspec, ignore_ws=False):
"""Return a list of parent :class:`~models_cisco.IOSCfgLine` objects, which matched the ``parentspec`` and whose children did not match ``childspec``. Only the parent :class:`~models_cisco.IOSCfgLine` objects will be returned. For simplicity, this method only finds oldest_ancestors without immediate children that match.
Args:
- parentspec (str): Text regular expression for the :class:`~models_cisco.IOSCfgLine` object to be matched; this must match the parent's line
- childspec (str): Text regular expression for the line to be matched; this must match the child's line
Kwargs:
- ignore_ws (bool): boolean that controls whether whitespace is ignored
Returns:
- list. A list of matching parent configuration lines
This example finds all ports that are autonegotiating in the following config...
.. code::
!
interface FastEthernet0/1
switchport access vlan 532
spanning-tree vlan 532 cost 3
!
interface FastEthernet0/2
switchport access vlan 300
spanning-tree portfast
!
interface FastEthernet0/2
duplex full
speed 100
switchport access vlan 300
spanning-tree portfast
!
The following interfaces should be returned:
.. code::
interface FastEthernet0/1
interface FastEthernet0/2
We do this by quering `find_objects_wo_child()`; we set our
parent as `^interface` and set the child as `speed\s\d+` (a
regular-expression which matches the word 'speed' followed by
an integer).
.. code-block:: python
:emphasize-lines: 18
>>> config = ['!',
... 'interface FastEthernet0/1',
... ' switchport access vlan 532',
... ' spanning-tree vlan 532 cost 3',
... '!',
... 'interface FastEthernet0/2',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... '!',
... 'interface FastEthernet0/3',
... ' duplex full',
... ' speed 100',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... '!',
... ]
>>> p = CiscoConfParse(config)
>>> p.find_objects_wo_child(r'^interface', r'speed\s\d+')
[<IOSCfgLine # 1 'interface FastEthernet0/1'>, <IOSCfgLine # 5 'interface FastEthernet0/2'>]
>>>
"""
if ignore_ws:
parentspec = self._build_space_tolerant_regex(parentspec)
childspec = self._build_space_tolerant_regex(childspec)
return [obj for obj in self.find_objects(parentspec)
if not obj.re_search_children(childspec)]
def find_parents_wo_child(self, parentspec, childspec, ignore_ws=False):
"""Parse through all parents matching parentspec, and return a list of parents that did NOT have children match the childspec. For simplicity, this method only finds oldest_ancestors without immediate children that match.
Args:
- parentspec (str): Text regular expression for the line to be matched; this must match the parent's line
- childspec (str): Text regular expression for the line to be matched; this must match the child's line
Kwargs:
- ignore_ws (bool): boolean that controls whether whitespace is ignored
Returns:
- list. A list of matching parent configuration lines
This example finds all ports that are autonegotiating in the
following config...
.. code::
!
interface FastEthernet0/1
switchport access vlan 532
spanning-tree vlan 532 cost 3
!
interface FastEthernet0/2
switchport access vlan 300
spanning-tree portfast
!
interface FastEthernet0/2
duplex full
speed 100
switchport access vlan 300
spanning-tree portfast
!
The following interfaces should be returned:
.. code::
interface FastEthernet0/1
interface FastEthernet0/2
We do this by quering `find_parents_wo_child()`; we set our
parent as `^interface` and set the child as `speed\s\d+` (a
regular-expression which matches the word 'speed' followed by
an integer).
.. code-block:: python
:emphasize-lines: 18
>>> config = ['!',
... 'interface FastEthernet0/1',
... ' switchport access vlan 532',
... ' spanning-tree vlan 532 cost 3',
... '!',
... 'interface FastEthernet0/2',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... '!',
... 'interface FastEthernet0/3',
... ' duplex full',
... ' speed 100',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... '!',
... ]
>>> p = CiscoConfParse(config)
>>> p.find_parents_wo_child('^interface', 'speed\s\d+')
['interface FastEthernet0/1', 'interface FastEthernet0/2']
>>>
"""
tmp = self.find_objects_wo_child(parentspec, childspec,
ignore_ws=ignore_ws)
return list(map(attrgetter('text'), tmp))
def find_children_w_parents(self, parentspec, childspec, ignore_ws=False):
"""Parse through the children of all parents matching parentspec,
and return a list of children that matched the childspec.
Args:
- parentspec (str): Text regular expression for the line to be matched; this must match the parent's line
- childspec (str): Text regular expression for the line to be matched; this must match the child's line
Kwargs:
- ignore_ws (bool): boolean that controls whether whitespace is ignored
Returns:
- list. A list of matching child configuration lines
This example finds the port-security lines on FastEthernet0/1 in
following config...