forked from mpenning/ciscoconfparse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ciscoconfparse.py
executable file
·1798 lines (1513 loc) · 67.2 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 operator import methodcaller, attrgetter
from collections import MutableSequence
from copy import deepcopy
from sys import modules
import time
import sys
import re
import os
from models_cisco import IOSHostnameLine, IOSRouteLine, IOSIntfLine
from models_cisco import IOSAccessLine, IOSIntfGlobal
from models_cisco import IOSCfgLine
### ipaddr is optional, and Apache License 2.0 is compatible with GPLv3 per
### the ASL web page: http://www.apache.org/licenses/GPL-compatibility.html
try:
from ipaddr import IPv4Network, IPv6Network
except ImportError:
# I raise an ImportError below ipaddr is required
pass
""" ciscoconfparse.py - Parse, Query, Build, and Modify IOS-style configurations
Copyright (C) 2007-2014 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_tuple__ = (0,9,28)
__version__ = '.'.join(map(str, __version_tuple__))
__email__ = "mike /at\ pennington [dot] net"
__author__ = "David Michael Pennington <{0}>".format(__email__)
__copyright__ = "2007-{0}, {1}".format(time.strftime('%Y'), __author__)
__license__ = "GPL"
__status__ = "Production"
class CiscoConfParse(object):
"""Parses Cisco IOS configurations and answers queries about the configs
Parameters
----------
config : :py:func:`list` or :py:func:`str`
A list of configuration statements, or a configuration file
path to be parsed
comment : :py:func:`str`, optional
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 '!'
Returns
-------
CiscoConfParse : :py:func:`object`
An instance of a CiscoConfParse object.
Attributes
----------
ConfigObjs : :py:func:`dict`
This contains all :class:`IOSCfgLine` object instances, which are generated from the configuration that is parsed. The :py:func:`dict` is keyed by an :py:func:`int`, which is the line number of the configuration line. The value of the :py:func:`dict` is the :class:`IOSCfgLine` instance for that line number.
Examples
--------
>>> config = [
... 'logging trap debugging',
... 'logging 172.28.26.15',
... ]
>>> p = CiscoConfParse(config)
>>> p
<CiscoConfParse: 2 lines / comment delimiter: '!' / factory: False>
>>> p.ConfigObjs
<IOSConfigList, comment='!', conf=[<IOSCfgLine # 0 'logging trap debugging'>, <IOSCfgLine # 1 'logging 172.28.26.15'>]>
>>>
"""
def __init__(self, config="", comment="!", debug=False, factory=False,
linesplit_rgx=r"\r*\n+"):
"""Initialize the class, read the config, and spawn the parser"""
# re: modules usage... thank you Delnan
# http://stackoverflow.com/a/5027393
if (factory is True) and (bool(modules.get('ipaddr', False)) is False):
from local.ipaddr import IPv4Network, IPv6Network
#raise ImportError("Could not import ipaddr module. ciscoconfparse.CiscoConfParse only requires the ipaddr module when called with factory=True.")
# all IOSCfgLine object instances...
self.comment_delimiter = comment
self.factory = factory
self.ConfigObjs = None
if isinstance(config, list):
# we already have a list object, simply call the parser
self.ConfigObjs = IOSConfigList(config, comment, debug, factory)
elif isinstance(config, str):
# Try opening as a file
try:
# string - assume a filename... open file, split and parse
f = open(config)
text = f.read()
rgx = re.compile(linesplit_rgx)
self.ConfigObjs = IOSConfigList(rgx.split(text), comment, debug,
factory)
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 / comment delimiter: '%s' / factory: %s>" % (len(self.ConfigObjs), self.comment_delimiter, self.factory)
@property
def ioscfg(self):
## I keep this here to emulate the legacy ciscoconfparse behavior
return [obj.text for obj in self.ConfigObjs]
@property
def objs(self):
return self.ConfigObjs
def atomic(self):
"""Call this to manually fix up ConfigObjs relationships after non-atomic insertions / deletions"""
self.ConfigObjs._bootstrap_from_text()
def commit(self):
"""Alias for calling the atomic() method"""
self.atomic()
def find_objects(self, linespec, exactmatch=False, ignore_ws=False):
if ignore_ws:
linespec = self._build_space_tolerant_regex(linespec)
#tmp = IOSConfigList()
#tmp.CiscoConfParse = self
#for obj in self._find_line_OBJ(linespec, exactmatch):
# tmp._list.append(obj)
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).
Parameters
----------
linespec : :py:func:`str`
Text regular expression for the line to be matched
exactmatch : :py:func:`bool`
boolean that controls whether partial matches are valid
ignore_ws : :py:func:`bool`
boolean that controls whether whitespace is ignored
Returns
-------
retval : :py:func:`list`
A list of matching configuration lines
"""
retval = list()
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.
Parameters
----------
linespec : :py:func:`str`
Text regular expression for the line to be matched
exactmatch : :py:func:`bool`
boolean that controls whether partial matches are valid
ignore_ws : :py:func:`bool`
boolean that controls whether whitespace is ignored
Returns
-------
retval : :py:func:`list`
A list of matching configuration lines
Examples
--------
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')`...
>>> 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.
Parameters
----------
linespec : :py:func:`str`
Text regular expression for the line to be matched
exactmatch : :py:func:`bool`
boolean that controls whether partial matches are valid
ignore_ws : :py:func:`bool`
boolean that controls whether whitespace is ignored
Returns
-------
retval : :py:func:`list`
A list of matching configuration lines
Examples
--------
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')`...
>>> 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:
if (parent.has_children is True):
allobjs.update(set(self._find_all_child_OBJ(parent)))
allobjs.add(parent)
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.
Parameters
----------
linespec : :py:func:`str`
Text regular expression for the line to be matched
exactmatch : :py:func:`bool`
boolean that controls whether partial matches are valid
ignore_ws : :py:func:`bool`
boolean that controls whether whitespace is ignored
Returns
-------
retval : :py:func:`list`
A list of matching configuration lines
Examples
--------
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')`...
>>> 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([])
retval = list()
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_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.
Parameters
----------
parentspec : :py:func:`str`
Text regular expression for the line to be matched; this must
match the parent's line
childspec : :py:func:`str`
Text regular expression for the line to be matched; this must
match the child's line
exactmatch : :py:func:`bool`
boolean that controls whether partial matches are valid
ignore_ws : :py:func:`bool`
boolean that controls whether whitespace is ignored
Returns
-------
retval : :py:func:`list`
A list of matching parent configuration lines
Examples
--------
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`.
>>> 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']
>>>
"""
if ignore_ws:
parentspec = self._build_space_tolerant_regex(parentspec)
childspec = self._build_space_tolerant_regex(childspec)
retval = set([])
childobjs = self._find_line_OBJ(childspec)
parentspec_re = re.compile(parentspec)
for child in childobjs:
parents = child.all_parents
match_parentspec = False
for parent in parents:
if parentspec_re.search(parent.text):
match_parentspec = True
if (match_parentspec is True):
for parent in parents:
retval.add(parent)
return list(map(attrgetter('text'), sorted(retval)))
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.
Parameters
----------
parentspec : :py:func:`str`
Text regular expression for the line to be matched; this must
match the parent's line
childspec : :py:func:`str`
Text regular expression for the line to be matched; this must
match the child's line
exactmatch : :py:func:`bool`
boolean that controls whether partial matches are valid
ignore_ws : :py:func:`bool`
boolean that controls whether whitespace is ignored
Returns
-------
retval : :py:func:`list`
A list of matching parent configuration lines
Examples
--------
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).
>>> 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']
>>>
"""
if ignore_ws:
parentspec = self._build_space_tolerant_regex(parentspec)
childspec = self._build_space_tolerant_regex(childspec)
retval = set([])
## Iterate over all parents, find those with non-matching children
for parentobj in [obj for obj in self.ConfigObjs.all_parents \
if (obj.oldest_ancestor and obj.re_search(parentspec))]:
match_childspec = False
for childobj in parentobj.children:
if childobj.re_search(childspec):
match_childspec = True
if (match_childspec is False):
## We found a parent without a child matching the
## childspec
retval.add(parentobj)
return list(map(attrgetter('text'), sorted(retval)))
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.
Parameters
----------
parentspec : :py:func:`str`
Text regular expression for the line to be matched; this must
match the parent's line
childspec : :py:func:`str`
Text regular expression for the line to be matched; this must
match the child's line
exactmatch : :py:func:`bool`
boolean that controls whether partial matches are valid
ignore_ws : :py:func:`bool`
boolean that controls whether whitespace is ignored
Returns
-------
retval : :py:func:`list`
A list of matching child configuration lines
Examples
--------
This example finds the port-security lines on FastEthernet0/1 in
following config...
.. code::
!
interface FastEthernet0/1
switchport access vlan 532
switchport port-security
switchport port-security violation protect
switchport port-security aging time 5
switchport port-security aging type inactivity
spanning-tree portfast
spanning-tree bpduguard enable
!
interface FastEthernet0/2
switchport access vlan 300
spanning-tree portfast
spanning-tree bpduguard enable
!
interface FastEthernet0/2
duplex full
speed 100
switchport access vlan 300
spanning-tree portfast
spanning-tree bpduguard enable
!
The following lines should be returned:
.. code::
switchport port-security
switchport port-security violation protect
switchport port-security aging time 5
switchport port-security aging type inactivity
We do this by quering `find_children_w_parents()`; we set our
parent as `^interface` and set the child as
`switchport port-security`.
>>> config = ['!',
... 'interface FastEthernet0/1',
... ' switchport access vlan 532',
... ' switchport port-security',
... ' switchport port-security violation protect',
... ' switchport port-security aging time 5',
... ' switchport port-security aging type inactivity',
... ' spanning-tree portfast',
... ' spanning-tree bpduguard enable',
... '!',
... 'interface FastEthernet0/2',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... ' spanning-tree bpduguard enable',
... '!',
... 'interface FastEthernet0/3',
... ' duplex full',
... ' speed 100',
... ' switchport access vlan 300',
... ' spanning-tree portfast',
... ' spanning-tree bpduguard enable',
... '!',
... ]
>>> p = CiscoConfParse(config)
>>> p.find_children_w_parents('^interface\sFastEthernet0/1', \
'port-security')
[' switchport port-security', ' switchport port-security violation protect', ' switchport port-security aging time 5', ' switchport port-security aging type inactivity']
>>>
"""
if ignore_ws:
parentspec = self._build_space_tolerant_regex(parentspec)
childspec = self._build_space_tolerant_regex(childspec)
retval = set([])
childobjs = self._find_line_OBJ(childspec)
parentspec_re = re.compile(parentspec)
childspec_re = re.compile(childspec)
for child in childobjs:
parents = child.all_parents
match_parentspec = False
for parent in parents:
if re.search(parentspec, parent.text):
retval.add(child)
return list(map(attrgetter('text'), sorted(retval)))
def find_lineage(self, linespec, exactmatch=False):
"""Iterate through to the oldest ancestor of this object, and return
a list of all ancestors / children in the direct line. Cousins or
aunts / uncles are *not* returned. Note, all children
of this object are returned."""
tmp = self.find_objects(linespec, exactmatch=exactmatch)
if len(tmp)>1:
raise ValueError("linespec must be unique")
return [obj.text for obj in tmp[0].lineage]
def has_line_with(self, linespec):
return self.ConfigObjs.has_line_with(linespec)
def insert_before(self, linespec, insertstr="", exactmatch=False,
ignore_ws=False, atomic=True):
"""Find all objects whose text matches linespec, and insert 'insertstr' before those line objects"""
objs = self.find_objects(linespec, exactmatch, ignore_ws)
last_idx = len(objs) - 1
local_atomic = False & atomic
for idx, obj in enumerate(objs):
if (idx==last_idx):
local_atomic = True & atomic
self.ConfigObjs.insert_before(obj, insertstr,
atomic=local_atomic)
## Return the matching lines
return list(map(attrgetter('text'), sorted(objs)))
def insert_after(self, linespec, insertstr="", exactmatch=False,
ignore_ws=False, atomic=True):
"""Find all objects whose text matches linespec, and insert 'insertstr' after those line objects"""
objs = self.find_objects(linespec, exactmatch, ignore_ws)
last_idx = len(objs) - 1
local_atomic = False & atomic
for idx, obj in enumerate(objs):
if idx==last_idx:
local_atomic = True & atomic
self.ConfigObjs.insert_after(obj, insertstr,
atomic=local_atomic)
## Return the matching lines
return list(map(attrgetter('text'), sorted(objs)))
def insert_after_child(self, parentspec, childspec, insertstr="",
exactmatch=False, excludespec=None, ignore_ws=False, atomic=True):
"""Find all objects whose text matches linespec and have a child matching childspec, and insert 'insertstr' after those child objects"""
retval = list()
modified = False
for pobj in self._find_line_OBJ(parentspec, exactmatch=exactmatch):
if excludespec and re.search(excludespec, pobj.text):
# Exclude replacements on pobj lines which match excludespec
continue
for cobj in pobj.children:
if excludespec and re.search(excludespec, cobj.text):
# Exclude replacements on pobj lines which match excludespec
continue
elif re.search(childspec, cobj.text):
modified = True
retval.append(self.ConfigObjs.insert_after(cobj,
insertstr, atomic=False))
else:
pass
if modified:
self.ConfigObjs.maintain_obj_sanity()
return retval
def delete_lines(self, linespec, exactmatch=False, ignore_ws=False):
"""Find all objects whose text matches linespec, and delete it"""
objs = self.find_objects(linespec, exactmatch, ignore_ws)
last_idx = len(objs) - 1
#atomic = False
for idx, obj in enumerate(objs):
#if idx==last_idx:
# atomic = True
del self.ConfigObjs[obj.linenum]
def prepend_line(self, linespec):
"""Unconditionally insert linespec (a text line) at the top of the configuration"""
self.ConfigObjs.insert(0, linespec)
return self.ConfigObjs[0]
def append_line(self, linespec):
"""Unconditionally insert linespec (a text line) at the end of the configuration"""
retval = self.ConfigObjs.append(linespec)
return self.ConfigObjs[-1]
def replace_lines(self, linespec, replacestr, excludespec=None, exactmatch=False,
atomic=True):
"""This method is a text search and replace (Case-sensitive). You can
optionally exclude lines from replacement by including a string (or
compiled regular expression) in `excludespec`.
Parameters
----------
linespec : :py:func:`str`
Text regular expression for the line to be matched
replacestr : :py:func:`str`
Text used to replace strings matching linespec
excludespec : :py:func:`str`
Text regular expression used to reject lines, which would
otherwise be replaced
exactmatch : :py:func:`bool`
boolean that controls whether partial matches are valid
atomic : :py:func:`bool`
boolean that controls whether the config is reparsed after replacement (default True)
Returns
-------
retval : :py:func:`list`
A list of changed configuration lines
Examples
--------
This example finds statements with `EXTERNAL_CBWFQ` in following
config, and replaces all matching lines (in-place) with `EXTERNAL_QOS`.
For the purposes of this example, let's assume that we do *not* want
to make changes to any descriptions on the policy.
.. code::
!
policy-map EXTERNAL_CBWFQ
description implement an EXTERNAL_CBWFQ policy
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
!
We do this by calling `replace_lines(linespec='EXTERNAL_CBWFQ',
replacestr='EXTERNAL_QOS', excludespec='description')`...
>>> from ciscoconfparse import CiscoConfParse
>>> config = ['!',
... 'policy-map EXTERNAL_CBWFQ',
... ' description implement an EXTERNAL_CBWFQ policy',
... ' 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.replace_lines('EXTERNAL_CBWFQ', 'EXTERNAL_QOS', 'description')
['policy-map EXTERNAL_QOS', ' service-policy EXTERNAL_QOS']
>>>
Now when we call `p.find_blocks('policy-map EXTERNAL_QOS')`, we get the
changed configuration, which has the replacements except on the
policy-map's description.
>>> p.find_blocks('EXTERNAL_QOS')
['policy-map EXTERNAL_QOS', ' description implement an EXTERNAL_CBWFQ policy', ' class IP_PREC_HIGH', ' class IP_PREC_MEDIUM', ' class class-default', 'policy-map SHAPE_HEIR', ' class ALL', ' shape average 630000', ' service-policy EXTERNAL_QOS']
>>>
"""
retval = list()
## Since we are replacing text, we *must* operate on ConfigObjs
if excludespec:
excludespec_re = re.compile(excludespec)
for obj in self._find_line_OBJ(linespec, exactmatch=exactmatch):
if excludespec and excludespec_re.search(obj.text):
# Exclude replacements on lines which match excludespec
continue
retval.append(obj.re_sub(linespec, replacestr))
if self.factory and atomic:
#self.ConfigObjs._reassign_linenums()
self.ConfigObjs._bootstrap_from_text()
return retval
def replace_children(self, parentspec, childspec, replacestr,
excludespec=None, exactmatch=False, atomic=True):
"""Replace lines matching `childspec` within the immediate children of lines which match `parentspec`"""
retval = list()
## Since we are replacing text, we *must* operate on ConfigObjs
childspec_re = re.compile(childspec)
if excludespec:
excludespec_re = re.compile(excludespec)
for pobj in self._find_line_OBJ(parentspec, exactmatch=exactmatch):
if excludespec and excludespec_re.search(pobj.text):
# Exclude replacements on pobj lines which match excludespec
continue
for cobj in pobj.children:
if excludespec and excludespec_re.search(cobj.text):
# Exclude replacements on pobj lines which match excludespec
continue