0
# Core Configuration Parsing
1
2
Comprehensive functionality for parsing, querying, and modifying network configurations. The CiscoConfParse class provides the primary interface for working with configuration files, supporting regex-based searches, parent-child relationship queries, and in-place modifications.
3
4
## Capabilities
5
6
### Configuration Parser Initialization
7
8
Initialize the parser with configuration data and syntax-specific options.
9
10
```python { .api }
11
class CiscoConfParse:
12
def __init__(
13
self,
14
config,
15
syntax='ios',
16
comment_delimiter='!',
17
debug=False,
18
factory=False,
19
ignore_blank_lines=True,
20
encoding='utf-8'
21
):
22
"""
23
Initialize configuration parser.
24
25
Parameters:
26
- config (str|list): Configuration file path, text, or list of lines
27
- syntax (str): Configuration syntax ('ios', 'nxos', 'asa', 'iosxr', 'junos')
28
- comment_delimiter (str): Character marking comment lines
29
- debug (bool): Enable debug logging
30
- factory (bool): Use factory parsing for enhanced object types
31
- ignore_blank_lines (bool): Skip blank lines during parsing
32
- encoding (str): File encoding for text files
33
"""
34
```
35
36
### Configuration Object Search
37
38
Find configuration objects matching specified patterns with support for exact matching and whitespace handling.
39
40
```python { .api }
41
def find_objects(self, linespec, exactmatch=False, ignore_ws=False):
42
"""
43
Find configuration objects matching linespec pattern.
44
45
Parameters:
46
- linespec (str): Regular expression pattern to match
47
- exactmatch (bool): Require exact string match instead of regex
48
- ignore_ws (bool): Ignore whitespace differences
49
50
Returns:
51
list: Configuration line objects matching the pattern
52
"""
53
54
def find_lines(self, linespec, exactmatch=False, ignore_ws=False):
55
"""
56
Find configuration line text matching linespec pattern.
57
58
Parameters:
59
- linespec (str): Regular expression pattern to match
60
- exactmatch (bool): Require exact string match instead of regex
61
- ignore_ws (bool): Ignore whitespace differences
62
63
Returns:
64
list[str]: Configuration line text matching the pattern
65
"""
66
67
def find_blocks(self, linespec, exactmatch=False, ignore_ws=False):
68
"""
69
Find configuration blocks starting with linespec pattern.
70
71
Parameters:
72
- linespec (str): Regular expression pattern to match parent lines
73
- exactmatch (bool): Require exact string match instead of regex
74
- ignore_ws (bool): Ignore whitespace differences
75
76
Returns:
77
list[list]: Lists of configuration lines, each starting with matching parent
78
"""
79
80
def find_object_branches(self, branchspec=(), regex_flags=0, allow_none=True, regex_groups=False, debug=0):
81
"""
82
Find nested object hierarchies matching complex branch specifications.
83
84
Parameters:
85
- branchspec (tuple): Nested regex patterns for hierarchical matching
86
- regex_flags (int): Regex compilation flags
87
- allow_none (bool): Allow None matches in branches
88
- regex_groups (bool): Return regex groups in results
89
- debug (int): Debug level
90
91
Returns:
92
list: Nested configuration object hierarchies
93
"""
94
95
def find_objects_dna(self, dnaspec, exactmatch=False):
96
"""
97
Find objects using DNA matching patterns.
98
99
Parameters:
100
- dnaspec (str): DNA specification pattern
101
- exactmatch (bool): Require exact matching
102
103
Returns:
104
list: Configuration objects matching DNA pattern
105
"""
106
```
107
108
### Hierarchical Relationship Queries
109
110
Search based on parent-child relationships in configuration hierarchy.
111
112
```python { .api }
113
def find_children(self, linespec, exactmatch=False, ignore_ws=False):
114
"""
115
Find direct child lines of configuration objects matching linespec.
116
117
Parameters:
118
- linespec (str): Regular expression pattern for parent lines
119
- exactmatch (bool): Require exact string match instead of regex
120
- ignore_ws (bool): Ignore whitespace differences
121
122
Returns:
123
list: Child configuration objects of matching parents
124
"""
125
126
def find_all_children(self, linespec, exactmatch=False, ignore_ws=False):
127
"""
128
Find all descendant lines of configuration objects matching linespec.
129
130
Parameters:
131
- linespec (str): Regular expression pattern for parent lines
132
- exactmatch (bool): Require exact string match instead of regex
133
- ignore_ws (bool): Ignore whitespace differences
134
135
Returns:
136
list: All descendant configuration objects of matching parents
137
"""
138
139
def find_objects_w_child(self, parentspec, childspec, ignore_ws=False):
140
"""
141
Find parent objects that have children matching childspec.
142
143
Parameters:
144
- parentspec (str): Regular expression pattern for parent lines
145
- childspec (str): Regular expression pattern for required child lines
146
- ignore_ws (bool): Ignore whitespace differences
147
148
Returns:
149
list: Parent configuration objects with matching children
150
"""
151
152
def find_parents_w_child(self, parentspec, childspec, ignore_ws=False):
153
"""
154
Find parent line text that has children matching childspec.
155
156
Parameters:
157
- parentspec (str): Regular expression pattern for parent lines
158
- childspec (str): Regular expression pattern for required child lines
159
- ignore_ws (bool): Ignore whitespace differences
160
161
Returns:
162
list[str]: Parent configuration line text with matching children
163
"""
164
165
def find_objects_wo_child(self, parentspec, childspec, ignore_ws=False):
166
"""
167
Find parent objects that do NOT have children matching childspec.
168
169
Parameters:
170
- parentspec (str): Regular expression pattern for parent lines
171
- childspec (str): Regular expression pattern for excluded child lines
172
- ignore_ws (bool): Ignore whitespace differences
173
174
Returns:
175
list: Parent configuration objects without matching children
176
"""
177
178
def find_objects_w_all_children(self, parentspec, childspec, ignore_ws=False, recurse=False):
179
"""
180
Find parent objects that have ALL specified children.
181
182
Parameters:
183
- parentspec (str): Regular expression pattern for parent lines
184
- childspec (list): List of required child patterns
185
- ignore_ws (bool): Ignore whitespace differences
186
- recurse (bool): Search recursively in descendants
187
188
Returns:
189
list: Parent objects with all required children
190
"""
191
192
def find_objects_w_missing_children(self, parentspec, childspec, ignore_ws=False, recurse=False):
193
"""
194
Find parent objects missing some of the specified children.
195
196
Parameters:
197
- parentspec (str): Regular expression pattern for parent lines
198
- childspec (list): List of expected child patterns
199
- ignore_ws (bool): Ignore whitespace differences
200
- recurse (bool): Search recursively in descendants
201
202
Returns:
203
list: Parent objects missing required children
204
"""
205
206
def find_lineage(self, linespec, exactmatch=False):
207
"""
208
Find complete ancestry lineage for configuration objects.
209
210
Parameters:
211
- linespec (str): Regular expression pattern for target lines
212
- exactmatch (bool): Require exact string match
213
214
Returns:
215
list: Complete ancestry chains for matching objects
216
"""
217
```
218
219
### Interface-Specific Search
220
221
Specialized search functionality for network interface configurations.
222
223
```python { .api }
224
def find_interface_objects(self, linespec, exactmatch=False, ignore_ws=False):
225
"""
226
Find interface configuration objects matching linespec pattern.
227
228
Parameters:
229
- linespec (str): Regular expression pattern for interface lines
230
- exactmatch (bool): Require exact string match instead of regex
231
- ignore_ws (bool): Ignore whitespace differences
232
233
Returns:
234
list: Interface configuration objects matching the pattern
235
"""
236
```
237
238
### Advanced Search Methods
239
240
Regex-based search with type conversion and pattern matching.
241
242
```python { .api }
243
def re_search_children(self, regexspec, recurse=False):
244
"""
245
Search children using regex patterns.
246
247
Parameters:
248
- regexspec (str): Regular expression pattern
249
- recurse (bool): Search recursively in all descendants
250
251
Returns:
252
list: Children matching regex pattern
253
"""
254
255
def re_match_iter_typed(self, regexspec, group=1, result_type=str, default="", untyped_default=False, groupdict={}, recurse=False, debug=0):
256
"""
257
Advanced regex matching with automatic type conversion.
258
259
Parameters:
260
- regexspec (str): Regular expression pattern with groups
261
- group (int): Regex group number to extract
262
- result_type (type): Type to convert results to (str, int, float, etc.)
263
- default: Default value for failed matches
264
- untyped_default (bool): Use untyped default values
265
- groupdict (dict): Named group mappings
266
- recurse (bool): Search recursively
267
- debug (int): Debug level
268
269
Returns:
270
generator: Type-converted regex match results
271
"""
272
```
273
274
### Configuration Modification
275
276
Insert, delete, and replace configuration lines with automatic hierarchy management.
277
278
```python { .api }
279
def insert_before(self, linespec, insertstr, exactmatch=False, ignore_ws=False):
280
"""
281
Insert new configuration lines before existing lines matching linespec.
282
283
Parameters:
284
- linespec (str): Regular expression pattern for target lines
285
- insertstr (str|list): Configuration text to insert
286
- exactmatch (bool): Require exact string match instead of regex
287
- ignore_ws (bool): Ignore whitespace differences
288
289
Returns:
290
list: Inserted configuration line objects
291
"""
292
293
def insert_after(self, linespec, insertstr, exactmatch=False, ignore_ws=False):
294
"""
295
Insert new configuration lines after existing lines matching linespec.
296
297
Parameters:
298
- linespec (str): Regular expression pattern for target lines
299
- insertstr (str|list): Configuration text to insert
300
- exactmatch (bool): Require exact string match instead of regex
301
- ignore_ws (bool): Ignore whitespace differences
302
303
Returns:
304
list: Inserted configuration line objects
305
"""
306
307
def delete_lines(self, linespec, exactmatch=False, ignore_ws=False):
308
"""
309
Delete configuration lines matching linespec pattern.
310
311
Parameters:
312
- linespec (str): Regular expression pattern for lines to delete
313
- exactmatch (bool): Require exact string match instead of regex
314
- ignore_ws (bool): Ignore whitespace differences
315
316
Returns:
317
list: Deleted configuration line objects
318
"""
319
320
def replace_lines(self, linespec, replacestr, exactmatch=False, ignore_ws=False):
321
"""
322
Replace configuration lines matching linespec with new text.
323
324
Parameters:
325
- linespec (str): Regular expression pattern for lines to replace
326
- replacestr (str): Replacement configuration text
327
- exactmatch (bool): Require exact string match instead of regex
328
- ignore_ws (bool): Ignore whitespace differences
329
330
Returns:
331
list: New configuration line objects after replacement
332
"""
333
334
def sync_diff(self, cfgspec=None, ignore_order=True, remove_lines=True, debug=0):
335
"""
336
Synchronize configuration with target specification.
337
338
Parameters:
339
- cfgspec (list): Target configuration specification
340
- ignore_order (bool): Ignore line ordering in comparison
341
- remove_lines (bool): Remove lines not in target spec
342
- debug (int): Debug level
343
344
Returns:
345
list: Configuration changes needed for synchronization
346
"""
347
348
def replace_children(self, parentspec, childspec, replacestr, ignore_ws=False, exactmatch=False, excludespec=None, atomic=False):
349
"""
350
Replace child lines matching patterns under parent objects.
351
352
Parameters:
353
- parentspec (str): Parent line pattern
354
- childspec (str): Child line pattern to replace
355
- replacestr (str): Replacement text
356
- ignore_ws (bool): Ignore whitespace
357
- exactmatch (bool): Exact string matching
358
- excludespec (str): Pattern to exclude from replacement
359
- atomic (bool): Atomic operation
360
361
Returns:
362
list: Replaced configuration objects
363
"""
364
365
def replace_all_children(self, parentspec, replacestr, ignore_ws=False, exactmatch=False, atomic=False):
366
"""
367
Replace all children under parent objects.
368
369
Parameters:
370
- parentspec (str): Parent line pattern
371
- replacestr (str): Replacement text for all children
372
- ignore_ws (bool): Ignore whitespace
373
- exactmatch (bool): Exact string matching
374
- atomic (bool): Atomic operation
375
376
Returns:
377
list: Replaced configuration objects
378
"""
379
```
380
381
### Configuration Management
382
383
Commit changes and save configurations to files.
384
385
```python { .api }
386
def commit(self):
387
"""
388
Commit all pending configuration changes to the internal text list.
389
Must be called after modification operations to apply changes.
390
391
Returns:
392
list[str]: Updated configuration as list of text lines
393
"""
394
395
def save_as(self, filepath):
396
"""
397
Save current configuration to a file.
398
399
Parameters:
400
- filepath (str): Target file path for saving configuration
401
402
Returns:
403
str: Path of saved configuration file
404
"""
405
```
406
407
## Configuration Comparison
408
409
### Difference Detection
410
411
Compare configurations and generate difference reports.
412
413
```python { .api }
414
class Diff:
415
def __init__(self, old_config, new_config, syntax='ios'):
416
"""
417
Initialize configuration difference analyzer.
418
419
Parameters:
420
- old_config (str|list): Original configuration
421
- new_config (str|list): Updated configuration
422
- syntax (str): Configuration syntax type
423
"""
424
425
def get_diff(self):
426
"""
427
Generate configuration differences.
428
429
Returns:
430
dict: Difference analysis results
431
"""
432
433
class HDiff:
434
"""Hierarchical configuration difference analysis."""
435
436
class DiffObject:
437
"""Represents individual configuration differences."""
438
```
439
440
## Password Handling
441
442
### Cisco Password Decryption
443
444
Decrypt Cisco Type 7 and other password formats.
445
446
```python { .api }
447
class CiscoPassword:
448
def __init__(self, ep=None):
449
"""
450
Initialize password handler.
451
452
Parameters:
453
- ep (str): Encrypted password string
454
"""
455
456
def decrypt(self, ep):
457
"""
458
Decrypt Cisco password.
459
460
Parameters:
461
- ep (str): Encrypted password string
462
463
Returns:
464
str: Decrypted password text
465
"""
466
```
467
468
## Configuration Container
469
470
### ConfigList Container
471
472
Mutable sequence container for configuration line objects.
473
474
```python { .api }
475
class ConfigList:
476
def __init__(
477
self,
478
data,
479
comment_delimiter='!',
480
debug=False,
481
factory=False,
482
ignore_blank_lines=True,
483
syntax='ios',
484
ccp_ref=None
485
):
486
"""
487
Initialize configuration list container.
488
489
Parameters:
490
- data (list): Configuration data
491
- comment_delimiter (str): Comment line delimiter
492
- debug (bool): Enable debug mode
493
- factory (bool): Use factory parsing
494
- ignore_blank_lines (bool): Skip blank lines
495
- syntax (str): Configuration syntax
496
- ccp_ref: CiscoConfParse reference
497
"""
498
499
def append(self, val):
500
"""Add configuration line to end of list."""
501
502
def insert(self, index, val):
503
"""Insert configuration line at specified index."""
504
505
def __getitem__(self, key):
506
"""Get configuration line by index or slice."""
507
508
def __setitem__(self, key, val):
509
"""Set configuration line by index or slice."""
510
511
def __delitem__(self, key):
512
"""Delete configuration line by index or slice."""
513
```
514
515
## Usage Examples
516
517
### Basic Configuration Parsing
518
519
```python
520
from ciscoconfparse import CiscoConfParse
521
522
# Parse configuration file
523
parse = CiscoConfParse('switch_config.txt', syntax='ios')
524
525
# Find all VLAN configurations
526
vlans = parse.find_objects(r'^vlan \d+')
527
for vlan in vlans:
528
print(f"VLAN: {vlan.text}")
529
for child in vlan.children:
530
print(f" {child.text}")
531
```
532
533
### Hierarchical Queries
534
535
```python
536
# Find interfaces configured as trunks
537
trunk_interfaces = parse.find_objects_w_child(
538
parentspec=r'^interface',
539
childspec=r'switchport mode trunk'
540
)
541
542
# Find BGP neighbors with specific attributes
543
bgp_neighbors = parse.find_objects_w_child(
544
parentspec=r'router bgp',
545
childspec=r'neighbor.*remote-as'
546
)
547
```
548
549
### Configuration Modification
550
551
```python
552
# Add description to all interfaces
553
interfaces = parse.find_objects(r'^interface')
554
for intf in interfaces:
555
if not any('description' in child.text for child in intf.children):
556
parse.insert_after(intf.text, ' description MANAGED_BY_AUTOMATION')
557
558
# Commit and save changes
559
parse.commit()
560
parse.save_as('updated_config.txt')
561
```