├── .gitignore ├── LICENSE ├── README.md ├── compiled_config ├── hierarchical_configuration.py ├── main.yml ├── running_config ├── test.py └── text_match.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hierarchical_configuration 2 | A library to compare Cisco IOS, NX-OS, and IOS-XR configurations 3 | -------------------------------------------------------------------------------- /compiled_config: -------------------------------------------------------------------------------- 1 | ip access-list extended vty 2 | permit ip host 10.4.1.9 any 3 | permit ip host 69.20.0.4 any 4 | permit ip host 69.20.0.12 any 5 | permit ip any 10.4.106.0 0.0.0.255 6 | permit ip 10.0.150.0 0.127.0.255 any 7 | permit ip 10.0.125.0 0.127.0.255 any 8 | permit ip 10.4.108.0 0.0.0.15 any 9 | permit ip host 10.4.126.56 any 10 | permit ip 10.0.255.64 0.127.0.31 any 11 | ! 12 | router ospf 65000 13 | max-metric router-lsa summary-lsa external-lsa on-startup wait-for-bgp 14 | ispf 15 | log-adjacency-changes 16 | auto-cost reference-bandwidth 1000000 17 | ! 18 | router bgp 65000 19 | no bgp default ipv4-unicast 20 | bgp log-neighbor-changes 21 | neighbor RR-Client peer-group 22 | neighbor RR-Client remote-as 65000 23 | neighbor RR-Client update-source Loopback0 24 | neighbor 10.4.2.234 remote-as 65000 25 | neighbor 10.4.2.234 peer-group RR-Client 26 | neighbor 10.4.2.234 description RR1B 27 | neighbor 10.4.2.235 remote-as 65000 28 | neighbor 10.4.2.235 peer-group RR-Client 29 | neighbor 10.4.2.235 description RR1A 30 | neighbor 2001:4802:800:C5:5001:C1:5:1 remote-as 65000 31 | neighbor 2001:4802:800:C5:5001:C1:5:1 inherit peer-session SERVICENET_V6 32 | maximum-paths ibgp 8 33 | ! 34 | address-family ipv4 35 | neighbor RR-Client soft-reconfiguration inbound 36 | neighbor 10.4.2.234 activate 37 | neighbor 10.4.2.235 activate 38 | maximum-paths ibgp 8 39 | no auto-summary 40 | no synchronization 41 | exit-address-family 42 | ! 43 | address-family ipv6 44 | neighbor 2001:4802:800:C5:5001:C1:5:1 activate 45 | neighbor 2001:4802:800:C5:5001:C1:5:1 inherit peer-policy SERVICENET_V6 46 | no synchronization 47 | maximum-paths ibgp 8 48 | exit-address-family 49 | -------------------------------------------------------------------------------- /hierarchical_configuration.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sys 3 | import copy 4 | from text_match import TextMatch 5 | 6 | class HierarchicalConfiguration(object): 7 | 8 | """ 9 | A class for representing and comparing Cisco running configurations in a 10 | hierarchical tree data structure. An instance represents one line of 11 | a configuration. Each instance has text, indentation, and a list of child items. 12 | 13 | Example usage: 14 | #Setup variables needed by HierarchicalConfiguration 15 | hier_tags = self.host_variable_space['hier_tags'] 16 | hier_options = dict() 17 | hier_options.update(self.host_variable_space['hier_options']) 18 | 19 | #Build HierarchicalConfiguration object for the Running Config 20 | running_config_hier = HierarchicalConfiguration(options=hier_options) 21 | running_config_hier.from_file(self.options['running_config_file']) 22 | print running_config_hier.logs.getvalue() 23 | 24 | #Build HierarchicalConfiguration object for the Compiled Config 25 | compiled_config_hier = HierarchicalConfiguration(options=hier_options) 26 | compiled_config_hier.from_file(self.options['compiled_config_file']) 27 | print running_config_hier.logs.getvalue() 28 | 29 | #Build HierarchicalConfiguration object for the Remediation Config 30 | remediation_config_hier = compiled_config_hier.deep_diff_tree_with(running_config_hier) 31 | remediation_config_hier.add_sectional_exiting() 32 | remediation_config_hier.add_tags(hier_tags) 33 | remediation_config = remediation_config_hier.to_detailed_ouput() 34 | print remediation_config_hier.logs.getvalue() 35 | 36 | 37 | #Example supporting data structures 38 | hier_options: 39 | #Enabled/Disables idempotent ACL handling for IOS-XR 40 | idempotent_acl_iosxr: true 41 | 42 | #if there is a delta, overwrite these parents instead of one of their children 43 | sectional_overwrite: 44 | - ^template 45 | 46 | sectional_overwrite_no_negate: 47 | - ^as-path-set 48 | - ^prefix-set 49 | - ^route-policy 50 | - ^extcommunity-set 51 | - ^community-set 52 | 53 | parent_allows_duplicate_child: 54 | - ^route-policy 55 | 56 | sectional_exiting: 57 | - parent_expression: ^route-policy 58 | exit_text: end-policy 59 | - parent_expression: ^policy-map 60 | exit_text: end-policy-map 61 | 62 | #adds +1 indent to lines following start_expression and removes the +1 indent for lines following end_expression 63 | indent_adjust: 64 | - start_expression: ^\s*template 65 | end_expression: ^\s*end-template 66 | 67 | #substitions against the full multi-line config text 68 | full_text_sub: 69 | - search: 'banner exec (\^?\S)\w*\n(.*\n)+\\1\s*\n' 70 | replace: '' 71 | - search: 'banner motd (\^?\S)\w*\n(.*\n)+\\1\s*\n' 72 | replace: '' 73 | 74 | #substitions against each line of the config text 75 | per_line_sub: 76 | - search: ^Building configuration.* 77 | replace: '' 78 | - search: .*message-digest-key.* 79 | replace: '' 80 | - search: .*password.* 81 | replace: '' 82 | 83 | idempotent_commands_blacklist: [] 84 | 85 | #These commands do not require negation, they simply overwrite themselves 86 | idempotent_commands: 87 | - ^\s*cost 88 | - logging \d+.\d+.\d+.\d+ vrf MGMT 89 | - soft-reconfiguration inbound 90 | 91 | #Default when expression: list of expressions 92 | negation_default_when: [] 93 | #- expressions 94 | 95 | #Negate substitutions: expression -> negate with 96 | negation_negate_with: [] 97 | #- match: expression 98 | # use: command 99 | 100 | hier_tags: 101 | safe: 102 | - lineage: 103 | - startswith: snmp 104 | action: add 105 | - lineage: 106 | - contains: ACL-VTY-IP 107 | action: add 108 | - lineage: 109 | - equals: policy-map INFRA_L3VPN 110 | action: add 111 | - lineage: 112 | - startswith: router bgp 113 | - startswith: neighbor-group 114 | - startswith: address-family 115 | - re_search: route-policy (DENY|DROP) 116 | action: add 117 | - lineage: 118 | - startswith: interface 119 | - equals: no carrier-delay up 0 down 0 120 | action: add 121 | pacl: 122 | - lineage: 123 | - startswith: ipv4 access-list pacl_ipv4 124 | action: add 125 | - lineage: 126 | - startswith: ipv6 access-list pacl_ipv6 127 | action: add 128 | """ 129 | 130 | def __init__( 131 | self, parent=None, text=None, indent_level=None, options=None): 132 | 133 | if text is None: 134 | self.text = text 135 | else: 136 | self.text = text.strip() 137 | 138 | self.parent = parent 139 | if self._is_base_instance(): 140 | self.indent_level = -1 141 | self.options = options 142 | self.logs = list() 143 | else: 144 | self.indent_level = indent_level 145 | self.options = self.parent.options 146 | self.logs = self.parent.logs 147 | 148 | self.children = [] 149 | # The intent is for self.order_weight values to range from 1 to 999 150 | # with the default weight being 500 151 | self.order_weight = 500 152 | self.tags = [] 153 | self.comment = '' 154 | self.post_exec_sleep = 0 155 | self.post_exec_string = '' 156 | self.new_in_config = False 157 | 158 | def __repr__(self): 159 | return 'HierarchicalConfiguration({}, {})'.format( 160 | self.text, 161 | self.indent_level) 162 | 163 | def __str__(self): 164 | return self.text 165 | 166 | def __lt__(self, other): 167 | if self.order_weight < other.order_weight: 168 | return True 169 | else: 170 | return False 171 | 172 | def _is_base_instance(self): 173 | """ Check if this instance is the base instance in the hierarchy """ 174 | if self.parent is None: 175 | return True 176 | else: 177 | return False 178 | 179 | def _delete(self): 180 | """ Delete the current object from its parent """ 181 | self.parent.children[:] = [ 182 | c for c in self.parent.children if not id(self) == id(c)] 183 | 184 | def _child_exists(self, text): 185 | """ Determine if child exists given the text of the child """ 186 | for child in self.children: 187 | if child.text == text: 188 | return True 189 | return False 190 | 191 | def get_child(self, test, expression): 192 | """ Find a child by TextMatch rule. If it is not found, return None """ 193 | children = self.get_children(test, expression) 194 | if children: 195 | return children[0] 196 | else: 197 | return None 198 | 199 | def get_children(self, test, expression): 200 | """ Find all children matching a TextMatch rule and return them. """ 201 | 202 | matching_children = list() 203 | for child in self.children: 204 | if TextMatch.dict_call(test, child.text, expression): 205 | matching_children.append(child) 206 | return matching_children 207 | 208 | def del_child(self, text): 209 | """ Delete all children with the provided text """ 210 | self.children[:] = [c for c in self.children if c.text != text] 211 | 212 | @staticmethod 213 | def _lineage_eval_object_rules(rules, section): 214 | """ 215 | Evaluate a list of lineage object rules. 216 | All object rules must match in order to return True 217 | """ 218 | matches = 0 219 | for rule in rules: 220 | if rule['test'] == 'new_in_config': 221 | if rule['expression'] == section.new_in_config: 222 | matches += 1 223 | elif rule['test'] == 'negative_intersection_tags': 224 | if isinstance(rule['expression'], basestring): 225 | rule['expression'] = [rule['expression']] 226 | if not set(rule['expression']).intersection(section.tags): 227 | matches += 1 228 | if matches == len(rules): 229 | return True 230 | else: 231 | return False 232 | 233 | @staticmethod 234 | def _lineage_eval_text_match_rules(rules, text): 235 | """ 236 | Evaluate a list of lineage text_match rules. 237 | Only one text_match rule must match in order to return True 238 | """ 239 | for rule in rules: 240 | if TextMatch.dict_call(rule['test'], text, rule['expression']): 241 | return True 242 | return False 243 | 244 | @staticmethod 245 | def _explode_lineage_rule(rule): 246 | text_match_rules = list() 247 | object_rules = list() 248 | for k, v in rule.iteritems(): 249 | if k in ['new_in_config', 'negative_intersection_tags']: 250 | object_rules.append({'test': k, 'expression': v}) 251 | elif isinstance(v, list): 252 | text_match_rules += [{'test': k, 'expression': e} for e in v] 253 | else: 254 | text_match_rules += [{'test': k, 'expression': v}] 255 | return(object_rules, text_match_rules) 256 | 257 | def _lineage_test(self, rule, strip_negation=False): 258 | """ A generic test against a lineage of HierarchicalConfiguration objects """ 259 | lineage = self._lineage() 260 | if rule['lineage'] and 'match_leaf' in rule[ 261 | 'lineage'][0] and rule['lineage'][0]['match_leaf']: 262 | lineage = [lineage[-1]] 263 | del(rule['lineage'][0]['match_leaf']) 264 | 265 | if 'debug' in rule and rule['debug']: 266 | debug = True 267 | else: 268 | debug = False 269 | 270 | if not len(rule['lineage']) == len(lineage): 271 | return False 272 | 273 | matches = 0 274 | if debug: 275 | print "lineage_rule ", rule['lineage'] 276 | print "lineage ", [l.text for l in lineage] 277 | 278 | for lineage_rule, section in zip(rule['lineage'], lineage): 279 | object_rules, text_match_rules = HierarchicalConfiguration._explode_lineage_rule( 280 | lineage_rule) 281 | if debug: 282 | print "lineage_rule ", lineage_rule 283 | print "section.text ", section.text 284 | 285 | if not HierarchicalConfiguration._lineage_eval_object_rules( 286 | object_rules, section): 287 | if debug: 288 | print "object rule failed and fully failed" 289 | print " section.new_in_config", section.new_in_config 290 | print " section.tags", section.tags 291 | return False 292 | else: 293 | if debug: 294 | print "object rule passed" 295 | 296 | # This removes negations for each section but honestly, 297 | # we really only need to do this on the last one 298 | if strip_negation: 299 | if section.text.startswith('no '): 300 | text = section.text[3:] 301 | elif section.text.startswith('default '): 302 | text = section.text[8:] 303 | else: 304 | text = section.text 305 | else: 306 | text = section.text 307 | 308 | if HierarchicalConfiguration._lineage_eval_text_match_rules( 309 | text_match_rules, text): 310 | matches += 1 311 | if debug: 312 | print "rule text_match passed" 313 | continue 314 | else: 315 | if debug: 316 | print "rule text_match failed and fully failed" 317 | return False 318 | 319 | if matches == len(rule['lineage']): 320 | if debug: 321 | print "rule fully passed" 322 | return True 323 | else: 324 | if debug: 325 | print "rule fully failed" 326 | return False 327 | 328 | def _duplicate_child_allowed_check(self): 329 | """ Determine if duplicate(identical text) children are allowed under the parent """ 330 | for rule in self.options['parent_allows_duplicate_child']: 331 | if self._lineage_test(rule): 332 | return True 333 | return False 334 | 335 | def add_child( 336 | self, text, indent_level=None, alert_on_duplicate=False, idx=None): 337 | if idx is None: 338 | idx = len(self.children) 339 | """ Add a child instance of HierarchicalConfiguration """ 340 | if not self._child_exists(text): 341 | new_item = HierarchicalConfiguration(self, text, indent_level) 342 | self.children.insert(idx, new_item) 343 | return new_item 344 | elif self._duplicate_child_allowed_check(): 345 | new_item = HierarchicalConfiguration(self, text, indent_level) 346 | self.children.insert(idx, new_item) 347 | return new_item 348 | else: 349 | # If the child is already present and the parent does not allow 350 | # duplicate children, return the existing child 351 | if alert_on_duplicate: 352 | path = self._path() + [text] 353 | self.logs.append("Found a duplicate section: {}".format(path)) 354 | return self.get_child('equals', text) 355 | 356 | def _add_shallow_copy_of(self, child_to_add): 357 | """ Add a nested copy of a child to self""" 358 | new_child = self.add_child( 359 | copy.copy(child_to_add.text), 360 | copy.copy(child_to_add.indent_level) 361 | ) 362 | new_child.comment = copy.copy(child_to_add.comment) 363 | new_child.tags = copy.copy(child_to_add.tags) 364 | return new_child 365 | 366 | def _add_deep_copy_of(self, child_to_add): 367 | """ Add a nested copy of a child to self""" 368 | new_child = self._add_shallow_copy_of(child_to_add) 369 | for child in child_to_add.children: 370 | new_child._add_deep_copy_of(child) 371 | return new_child 372 | 373 | def _lineage(self): 374 | """ 375 | Return the lineage of parent objects, up to but excluding the root 376 | """ 377 | if self.parent: 378 | parents = self.parent._lineage() 379 | return parents + [self] 380 | else: 381 | return [] 382 | 383 | def _path(self): 384 | """ 385 | Return a list of the text instance variables from self.lineage 386 | """ 387 | path = [c.text for c in self._lineage()] 388 | return path 389 | 390 | def _cisco_style_text(self): 391 | """ Return a Cisco style formated line i.e. indentation_level + text """ 392 | the_text = "{}{}".format(" " * self.indent_level, self.text) 393 | return the_text 394 | 395 | # We will worry about this later 396 | # def type_7_password_decrypt(self, text): 397 | # decrypt=lambda x:''.join([chr(int(x[i:i+2],16)^ord('dsfd;kfoA,.iyewrkldJKDHSUBsgvca69834ncxv9873254k;fg87'[(int(x[:2])+i/2-1)%53]))for i in range(2,len(x),2)]) 398 | # return decrypt(text) 399 | 400 | def _all_children_sorted(self): 401 | """ Recursively find and return all children sorted at each hierarchy """ 402 | found_children = [] 403 | for child in sorted(self.children): 404 | found_children += child._all_children_sorted() 405 | if self._is_base_instance(): 406 | return found_children 407 | else: 408 | return [self] + found_children 409 | 410 | def _all_children(self): 411 | """ Recursively find and return all children """ 412 | found_children = [] 413 | for child in self.children: 414 | found_children += child._all_children() 415 | if self._is_base_instance(): 416 | return found_children 417 | else: 418 | return [self] + found_children 419 | 420 | def _sectional_overwrite_no_negate_check(self): 421 | """ 422 | Check self's text to see if negation should be handled by 423 | overwriting the section without first negating it 424 | """ 425 | for rule in self.options['sectional_overwrite_no_negate']: 426 | if self._lineage_test(rule): 427 | return True 428 | return False 429 | 430 | def _sectional_overwrite_check(self): 431 | """ Determines if self.text matches a sectional overwrite rule """ 432 | for rule in self.options['sectional_overwrite']: 433 | if self._lineage_test(rule): 434 | return True 435 | return False 436 | 437 | def _resequence_acl_check(self): 438 | """ 439 | Is the object an ACL and is ACL resequencing enabled 440 | """ 441 | if self.options['style'] in ['ios']: 442 | acl_sw = ('ip access-list') 443 | if self.text.startswith(acl_sw): 444 | return True 445 | return False 446 | 447 | def _resequence_acl(self, delta): 448 | """ Inserts an ACL resequence command """ 449 | acl_name = self.text.split(' ')[3] 450 | 451 | for idx, child in enumerate(delta.children): 452 | if child.text == self.text: 453 | index = idx 454 | break 455 | resquence = delta.add_child( 456 | "ip access-list resequence {} 10 10".format(acl_name), 457 | self.indent_level, 458 | idx=index 459 | ) 460 | resquence.comment = "added acl resequence" 461 | return delta 462 | 463 | def _overwrite_with(self, other, delta, negate=True): 464 | """ Deletes delta.child[self.text], adds a deep copy of self to delta """ 465 | if other.children != self.children: 466 | if negate: 467 | delta.del_child(self.text) 468 | deleted = delta.add_child( 469 | self.text, self.indent_level).negate() 470 | deleted.comment = "dropping entire section" 471 | if self.children: 472 | delta.del_child(self.text) 473 | new_item = delta._add_deep_copy_of(self) 474 | new_item.comment = "re-create section from scratch" 475 | return delta 476 | 477 | def set_order_weight(self): 478 | """ 479 | Sets self.order integer on all children 480 | """ 481 | for child in self._all_children(): 482 | for rule in self.options['ordering']: 483 | if child._lineage_test(rule): 484 | child.order_weight = rule['order'] 485 | 486 | def add_sectional_exiting(self): 487 | """ 488 | Adds the sectional exiting text as a child 489 | """ 490 | for child in self._all_children(): 491 | for rule in self.options['sectional_exiting']: 492 | if child._lineage_test(rule): 493 | if child._child_exists(rule['exit_text']): 494 | child.del_child(rule['exit_text']) 495 | 496 | new_child = child.add_child( 497 | rule['exit_text'], 498 | child._get_child_indent() 499 | ) 500 | new_child.order_weight = 999 501 | 502 | def _get_child_indent(self): 503 | """ Determines the child indent level and returns it """ 504 | if self.children: 505 | return self.children[0].indent_level 506 | else: 507 | return self.indent_level + 1 508 | 509 | def to_tag_spec(self, tags): 510 | """ 511 | Returns the configuration as a tag spec definition 512 | This is handy when you have a segment of config and need to 513 | generate a tag spec to tag configuration in another instance 514 | """ 515 | tag_spec = [] 516 | for child in self._all_children(): 517 | if not child.children: 518 | child_spec = [{'equals': t} for t in child._path()] 519 | tag_spec.append({'section': child_spec, 'add_tags': tags}) 520 | return tag_spec 521 | 522 | def add_tags(self, tag_rules, strip_negation=False): 523 | """ 524 | Handler for tagging sections of HierarchicalConfiguration data structure 525 | for inclusion and exclusion. 526 | """ 527 | for rule in tag_rules: 528 | for child in self._all_children(): 529 | if child._lineage_test(rule, strip_negation): 530 | if 'add_tags' in rule: 531 | child.deep_append_tags(rule['add_tags']) 532 | for ancestor in child.parent._lineage(): 533 | ancestor._append_tags(rule['add_tags']) 534 | if 'remove_tags' in rule: 535 | child.deep_remove_tags(rule['remove_tags']) 536 | 537 | return self 538 | 539 | def deep_append_tags(self, tags): 540 | """ 541 | Append tags to self.tags and recursively for all children 542 | """ 543 | self._append_tags(tags) 544 | for child in self._all_children(): 545 | child._append_tags(tags) 546 | 547 | def deep_remove_tags(self, tags): 548 | """ 549 | Remove tags from self.tags and recursively for all children 550 | """ 551 | self._remove_tags(tags) 552 | for child in self._all_children(): 553 | child._remove_tags(tags) 554 | 555 | def _append_tags(self, tags): 556 | """ 557 | Add tags to self.tags 558 | """ 559 | if isinstance(tags, basestring): 560 | tags = [tags] 561 | for tag in tags: 562 | if not tag in self.tags: 563 | self.tags.append(tag) 564 | 565 | def _remove_tags(self, tags): 566 | """ 567 | Remove tags from self.tags 568 | """ 569 | if isinstance(tags, basestring): 570 | tags = [tags] 571 | for tag in tags: 572 | if tag in self.tags: 573 | self.tags.remove(tag) 574 | 575 | def with_tags(self, tags, new_instance=None): 576 | """ 577 | Returns a new instance containing only sub-objects 578 | with one of the tags in tags 579 | """ 580 | if new_instance is None: 581 | new_instance = HierarchicalConfiguration(options=self.options) 582 | 583 | for child in self.children: 584 | if list(set(tags) & set(self.tags)): 585 | new_instance._add_shallow_copy_of(child) 586 | new_child.with_tags(tags, new_child) 587 | 588 | return new_instance 589 | 590 | def deep_diff_tree_with(self, other, delta=None): 591 | """ 592 | Figures out what commands need to be executed to transition from other to self. 593 | Self is the targat datastructure(i.e. the compiled template), other is the source(i.e. running-config) 594 | """ 595 | 596 | if delta is None: 597 | delta = HierarchicalConfiguration(options=self.options) 598 | 599 | # find other.children that are not in self.children - i.e. what needs to be negated or defaulted 600 | # Also, find out if another command in other.children will overwrite - 601 | # i.e. be idempotent 602 | for other_child in other.children: 603 | if self._child_exists(other_child.text): 604 | pass 605 | elif other_child._idempotent_command(self.children): 606 | pass 607 | else: 608 | # in other but not self 609 | # add this node but not any children 610 | deleted = delta.add_child( 611 | other_child.text, 612 | other_child.indent_level) 613 | deleted.negate() 614 | if other_child.children: 615 | deleted.comment = "removes {} lines".format( 616 | len(other_child._all_children()) + 1) 617 | 618 | # find what would need to be added to other to get to self 619 | for self_child in self.children: 620 | # if the child exist, recurse into its children 621 | if other._child_exists(self_child.text): 622 | other_child = other.get_child('equals', self_child.text) 623 | subtree = delta.add_child( 624 | self_child.text, 625 | self_child.indent_level) 626 | self_child.deep_diff_tree_with(other_child, subtree) 627 | if not subtree.children: 628 | subtree._delete() 629 | # If the line is an ACL, do we need to resequence it? 630 | elif other_child._resequence_acl_check(): 631 | self_child._resequence_acl(delta) 632 | # Do we need to rewrite the child and its children as well? 633 | elif other_child._sectional_overwrite_check(): 634 | self_child._overwrite_with(other_child, delta, True) 635 | elif other_child._sectional_overwrite_no_negate_check(): 636 | self_child._overwrite_with(other_child, delta, False) 637 | # if the child is absent, add it 638 | else: 639 | new_item = delta._add_deep_copy_of(self_child) 640 | # mark the new item and all of its children as new_in_config 641 | for child in new_item._all_children(): 642 | child.new_in_config = True 643 | if new_item.children: 644 | new_item.comment = "new section, didn't exist before" 645 | 646 | return delta 647 | 648 | def from_file(self, file_path): 649 | """ Load configuration text from a file """ 650 | with open(file_path, 'r') as f: 651 | config_text = f.read() 652 | self.from_config_text(config_text) 653 | 654 | def _add_acl_sequence_numbers(self): 655 | """ 656 | Add ACL sequence numbers for use on configurations with a style of 'ios' 657 | """ 658 | 659 | ipv4_acl_sw = ('ip access-list') 660 | #ipv6_acl_sw = ('ipv6 access-list') 661 | acl_line_sw = ('permit', 'deny', 'remark') 662 | for child in self.children: 663 | if child.text.startswith(ipv4_acl_sw): 664 | sn = 10 665 | for sub_child in child.children: 666 | if sub_child.text.startswith(acl_line_sw): 667 | sub_child.text = "{} {}".format(sn, sub_child.text) 668 | sn += 10 669 | # elif child.text.startswith(ipv6_acl_sw): 670 | # sn = 10 671 | # for sub_child in child.children: 672 | # if sub_child.text.startswith(acl_line_sw): 673 | # sub_child.text = "sequence {} {}".format(sn, sub_child.text) 674 | # sn += 10 675 | return self 676 | 677 | def from_config_text(self, config_text): 678 | """ Create HierarchicalConfiguration nested objects from text """ 679 | for sub in self.options['full_text_sub']: 680 | config_text = re.sub( 681 | sub['search'].decode( 682 | 'string_escape'), 683 | sub['replace'].decode( 684 | 'string_escape'), 685 | config_text) 686 | 687 | current_section = self 688 | current_section.indent_level = -1 689 | most_recent_item = current_section 690 | indent_adjust = 0 691 | end_indent_adjust = [] 692 | 693 | for line in config_text.splitlines(): 694 | line = line.rstrip('\n') 695 | for sub in self.options['per_line_sub']: 696 | line = re.sub( 697 | sub['search'].decode('string_escape'), 698 | sub['replace'].decode('string_escape'), 699 | line) 700 | line = line.rstrip() 701 | 702 | # If line is now empty, move to the next 703 | if not line: 704 | continue 705 | 706 | # Determine indentation level 707 | this_indent = len(line) - len(line.lstrip()) + indent_adjust 708 | 709 | line = line.lstrip() 710 | 711 | # Walks back up the tree 712 | while this_indent <= current_section.indent_level: 713 | current_section = current_section.parent 714 | 715 | # Walks down the tree by one step 716 | if this_indent > most_recent_item.indent_level: 717 | current_section = most_recent_item 718 | 719 | most_recent_item = current_section.add_child( 720 | line, 721 | this_indent, 722 | True) 723 | 724 | for expression in self.options['indent_adjust']: 725 | if re.search(expression['start_expression'], line): 726 | indent_adjust += 1 727 | end_indent_adjust.append(expression['end_expression']) 728 | break 729 | if end_indent_adjust and re.search(end_indent_adjust[0], line): 730 | indent_adjust -= 1 731 | del(end_indent_adjust[0]) 732 | 733 | if self.options['style'] in ['ios']: 734 | self._add_acl_sequence_numbers() 735 | 736 | return self 737 | 738 | def to_detailed_ouput(self): 739 | """ Returns a list of Cisco style formated lines with tags and comments""" 740 | lines = [] 741 | for child in self._all_children_sorted(): 742 | cisco_style_text_line = child._cisco_style_text() 743 | lines.append({ 744 | 'text': cisco_style_text_line, 745 | 'tags': child.tags, 746 | 'post_exec_sleep': child.post_exec_sleep, 747 | 'post_exec_string': child.post_exec_string, 748 | 'comment': child.comment 749 | }) 750 | 751 | return lines 752 | 753 | def _swap_negation(self): 754 | """ Swap negation of a self.text """ 755 | if self.text.startswith('no '): 756 | self.text = self.text[3:] 757 | else: 758 | self.text = 'no ' + self.text 759 | return self 760 | 761 | def _default(self): 762 | """ Default self.text """ 763 | if self.text.startswith('no '): 764 | self.text = 'default ' + self.text[3:] 765 | else: 766 | self.text = 'default ' + self.text 767 | return self 768 | 769 | def negate(self): 770 | """ Negate self.text """ 771 | for rule in self.options['negation_negate_with']: 772 | if self._lineage_test(rule): 773 | self.text = rule['use'] 774 | return self 775 | 776 | for rule in self.options['negation_default_when']: 777 | if self._lineage_test(rule): 778 | return self._default() 779 | 780 | return self._swap_negation() 781 | 782 | def _idempotent_acl_check(self): 783 | """ 784 | Handle conditional testing to determine if idempotent acl handling for iosxr should be used 785 | """ 786 | if self.options['style'] in ['iosxr']: 787 | if not self.parent._is_base_instance(): 788 | acl = ('ipv4 access-list', 'ipv6 access-list') 789 | if self.parent.text.startswith(acl): 790 | return True 791 | return False 792 | 793 | def _idempotent_command(self, other_children): 794 | """ 795 | Determine if self.text is an idempotent change. 796 | """ 797 | 798 | # Blacklist commands from matching as idempotent 799 | for rule in self.options['idempotent_commands_blacklist']: 800 | if self._lineage_test(rule, True): 801 | return False 802 | 803 | # Handles idempotent acl entry identification 804 | if self._idempotent_acl_check(): 805 | if self.options['style'] in ['iosxr']: 806 | self_sn = self.text.split(' ', 1)[0] 807 | for other_child in other_children: 808 | if self.options['style'] in ['iosxr']: 809 | other_sn = other_child.text.split(' ', 1)[0] 810 | if self_sn == other_sn: 811 | return True 812 | 813 | # Idempotent command identification 814 | for rule in self.options['idempotent_commands']: 815 | if self._lineage_test(rule, True): 816 | for other_child in other_children: 817 | if other_child._lineage_test(rule, True): 818 | return True 819 | 820 | return False 821 | -------------------------------------------------------------------------------- /main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | hier_tags: 3 | - lineage: 4 | - startswith: 5 | - ip access-list extended TEST 6 | - no ip access-list extended TEST 7 | add_tags: NEW_ACL 8 | - lineage: 9 | - startswith: interface 10 | - startswith: ip access-group TEST 11 | add_tags: NEW_ACL 12 | - lineage: 13 | - startswith: 14 | - ip domain-name 15 | - no ip domain-name 16 | - ip domain-lookup 17 | - no ip domain-lookup 18 | - logging 19 | - no logging 20 | - snmp-server 21 | - no snmp-server 22 | - ntp server 23 | - no ntp server 24 | - ip tcp path-mtu-discovery 25 | - ip access-list resequence 26 | add_tags: safe 27 | - lineage: 28 | - startswith: line 29 | - startswith: exec-timeout 30 | add_tags: safe 31 | - lineage: 32 | - startswith: interface 33 | - startswith: ip access-group 34 | add_tags: unsafe 35 | - lineage: 36 | - startswith: router ospf 37 | new_in_config: false 38 | - startswith: 39 | - ispf 40 | - nsf 41 | - log 42 | add_tags: safe 43 | - lineage: 44 | - startswith: router ospf 45 | new_in_config: false 46 | - startswith: 47 | - network 48 | - area 49 | add_tags: unsafe 50 | 51 | hier_options: 52 | #Indicates the style of the configuration 53 | style: ios 54 | 55 | #if there is a delta, overwrite these parents instead of one of their children 56 | sectional_overwrite: 57 | - lineage: 58 | - startswith: ipv6 access-list 59 | 60 | ordering: 61 | - lineage: 62 | - startswith: 63 | - ip access-list 64 | - access-list 65 | order: 300 66 | - lineage: 67 | - startswith: 68 | - tacacs-server host 69 | order: 400 70 | - lineage: 71 | - startswith: interface 72 | - startswith: 73 | - ip access-group 74 | - no ip access-group 75 | order: 400 76 | - lineage: 77 | - startswith: 78 | - no ip access-list 79 | - no access-list 80 | - no ip prefix-list 81 | - no tacacs-server host 82 | order: 590 83 | - lineage: 84 | - contains: ip spd queue min-threshold 85 | order: 601 86 | - lineage: 87 | - contains: ip spd queue max-threshold 88 | order: 602 89 | 90 | sectional_overwrite_no_negate: [] 91 | 92 | #adds +1 indent to lines following start_expression and removes the +1 indent for lines following end_expression 93 | indent_adjust: [] 94 | 95 | parent_allows_duplicate_child: [] 96 | 97 | sectional_exiting: 98 | - lineage: 99 | - startswith: router bgp 100 | - startswith: template peer-policy 101 | exit_text: exit-peer-policy 102 | - lineage: 103 | - startswith: router bgp 104 | - startswith: template peer-session 105 | exit_text: exit-peer-session 106 | - lineage: 107 | - startswith: router bgp 108 | - startswith: address-family 109 | exit_text: exit-address-family 110 | 111 | #substitions against the full multi-line config text 112 | full_text_sub: 113 | - search: 'banner exec (\S+)\n(.*\n)+\\1\s*\n' 114 | replace: '' 115 | - search: 'banner motd (\S+)\n(.*\n)+\\1\s*\n' 116 | replace: '' 117 | 118 | #substitions against each line of the config text 119 | per_line_sub: 120 | - search: ^Building configuration.* 121 | replace: '' 122 | - search: ^Current configuration.* 123 | replace: '' 124 | - search: ^! Last configuration change.* 125 | replace: '' 126 | - search: ^! NVRAM config last updated.* 127 | replace: '' 128 | - search: ^ntp clock-period .* 129 | replace: '' 130 | - search: .*message-digest-key.* 131 | replace: '' 132 | - search: ^version.* 133 | replace: '' 134 | - search: .*password.* 135 | replace: '' 136 | - search: ^ logging event link-status$ 137 | replace: '' 138 | - search: ^ logging event subif-link-status$ 139 | replace: '' 140 | - search: ^\s*ipv6 unreachables disable$ 141 | replace: '' 142 | - search: ^\s*key .* 143 | replace: '' 144 | - search: ^end$ 145 | replace: '' 146 | - search: '^\s*[#!].*' 147 | replace: '' 148 | - search: ^ no ip address 149 | replace: '' 150 | - search: ^ exit-peer-policy 151 | replace: '' 152 | - search: ^ exit-peer-session 153 | replace: '' 154 | - search: ^ exit-address-family 155 | replace: '' 156 | - search: ^crypto key generate rsa general-keys.*$ 157 | replace: '' 158 | - search: .*key-string.* 159 | replace: '' 160 | 161 | idempotent_commands_blacklist: [] 162 | 163 | #These commands do not require negation, they simply overwrite themselves 164 | idempotent_commands: 165 | - lineage: 166 | - startswith: hostname 167 | - lineage: 168 | - startswith: logging source-interface 169 | - lineage: 170 | - startswith: interface 171 | - startswith: description 172 | - lineage: 173 | - startswith: interface 174 | - startswith: ip address 175 | - lineage: 176 | - startswith: line vty 177 | - startswith: 178 | - transport input 179 | - access-class 180 | - ipv6 access-class 181 | - lineage: 182 | - startswith: interface 183 | - re_search: standby \d+ (priority|authentication md5) 184 | - lineage: 185 | - startswith: router bgp 186 | - startswith: bgp router-id 187 | - lineage: 188 | - startswith: router ospf 189 | - startswith: router-id 190 | - lineage: 191 | - startswith: ipv6 router ospf 192 | - startswith: router-id 193 | - lineage: 194 | - startswith: router ospf 195 | - startswith: log-adjacency-changes 196 | - lineage: 197 | - startswith: ipv6 router ospf 198 | - startswith: log-adjacency-changes 199 | - lineage: 200 | - startswith: router bgp 201 | - re_search: neighbor \S+ description 202 | - lineage: 203 | - startswith: snmp-server community 204 | - lineage: 205 | - startswith: snmp-server location 206 | - lineage: 207 | - equals: line con 0 208 | - startswith: exec-timeout 209 | - lineage: 210 | - startswith: interface 211 | - startswith: ip ospf message-digest-key 212 | - lineage: 213 | - startswith: logging buffered 214 | - lineage: 215 | - startswith: tacacs-server key 216 | - lineage: 217 | - startswith: logging facility 218 | - lineage: 219 | - startswith: vlan internal allocation policy 220 | 221 | #Default when expression: list of expressions 222 | negation_default_when: [] 223 | #- lineage: 224 | # - startswith: interface 225 | 226 | #Negate substitutions: expression -> negate with 227 | negation_negate_with: [] 228 | #- lineage: 229 | # - startswith: interface 230 | # use: command 231 | -------------------------------------------------------------------------------- /running_config: -------------------------------------------------------------------------------- 1 | ip access-list extended vty 2 | permit ip host 10.4.1.9 any 3 | permit ip any 10.4.106.0 0.0.0.255 4 | permit ip 10.0.150.0 0.127.0.255 any 5 | permit ip 10.0.125.0 0.127.0.255 any 6 | permit ip 10.4.108.0 0.0.0.15 any 7 | permit ip host 10.4.126.56 any 8 | permit ip 10.0.255.64 0.127.0.31 any 9 | ! 10 | router ospf 65000 11 | max-metric router-lsa summary-lsa external-lsa on-startup wait-for-bgp 12 | ispf 13 | log-adjacency-changes 14 | ! 15 | router bgp 65000 16 | no bgp default ipv4-unicast 17 | bgp log-neighbor-changes 18 | neighbor RR-Client peer-group 19 | neighbor RR-Client remote-as 65000 20 | neighbor RR-Client update-source Loopback0 21 | neighbor 10.4.2.234 remote-as 65000 22 | neighbor 10.4.2.234 peer-group RR-Client 23 | neighbor 10.4.2.234 description RR1B 24 | neighbor 2001:4802:800:C5:5001:C1:5:1 remote-as 65000 25 | neighbor 2001:4802:800:C5:5001:C1:5:1 inherit peer-session SERVICENET_V6 26 | maximum-paths ibgp 8 27 | ! 28 | address-family ipv4 29 | neighbor RR-Client soft-reconfiguration inbound 30 | neighbor 10.4.2.234 activate 31 | maximum-paths ibgp 8 32 | no auto-summary 33 | no synchronization 34 | exit-address-family 35 | ! 36 | address-family ipv6 37 | neighbor 2001:4802:800:C5:5001:C1:5:1 activate 38 | neighbor 2001:4802:800:C5:5001:C1:5:1 inherit peer-policy SERVICENET_V6 39 | no synchronization 40 | maximum-paths ibgp 8 41 | exit-address-family 42 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | from hierarchical_configuration import HierarchicalConfiguration 3 | 4 | class HierTest(object): 5 | 6 | def __init__(self, running_config, compiled_config): 7 | self.hier_options = self._load_hier_options() 8 | self.hier_tags = self._load_hier_tags() 9 | self.running_config_hier = self._load_running_config(running_config) 10 | self.compiled_config_hier = self._load_compiled_config(compiled_config) 11 | 12 | def _load_hier_options(self): 13 | """ 14 | load the appropriate HierarchicalConfiguration options 15 | """ 16 | with open('main.yml', 'r') as my_file: 17 | hier_options = yaml.load(my_file)['hier_options'] 18 | 19 | return hier_options 20 | 21 | def _load_hier_tags(self): 22 | """ 23 | Load the appropriate HierarchicalConfiguration tag definitions 24 | """ 25 | with open('main.yml', 'r') as my_file: 26 | hier_tags = yaml.load(my_file)['hier_tags'] 27 | 28 | return hier_tags 29 | 30 | def _load_running_config(self, running_config): 31 | """ 32 | Build HierarchicalConfiguration object for the Running Config 33 | """ 34 | running_config_hier = HierarchicalConfiguration( 35 | options=self.hier_options) 36 | running_config_hier.from_config_text(running_config) 37 | 38 | return running_config_hier 39 | 40 | def _load_compiled_config(self, compiled_config): 41 | """ 42 | Build HierarchicalConfiguration object for the Compiled Config 43 | """ 44 | compiled_config_hier = HierarchicalConfiguration( 45 | options=self.hier_options) 46 | compiled_config_hier.from_config_text(compiled_config) 47 | 48 | return compiled_config_hier 49 | 50 | def build_remediation(self): 51 | """ 52 | Build HierarchicalConfiguration object for the Remediation Config 53 | """ 54 | remediation_config_hier = self.compiled_config_hier.deep_diff_tree_with(self.running_config_hier) 55 | remediation_config_hier.set_order_weight() 56 | remediation_config_hier.add_sectional_exiting() 57 | remediation_config_hier.add_tags(self.hier_tags) 58 | 59 | return remediation_config_hier.to_detailed_ouput() 60 | 61 | with open('running_config', 'r') as myfile: 62 | running_config = '' 63 | for line in myfile.readlines(): 64 | running_config += line + '\n' 65 | 66 | with open('compiled_config', 'r') as myfile: 67 | compiled_config = '' 68 | for line in myfile.readlines(): 69 | compiled_config += line + '\n' 70 | 71 | hier = HierTest(running_config, compiled_config) 72 | 73 | for line in hier.build_remediation(): 74 | print line['text'] 75 | -------------------------------------------------------------------------------- /text_match.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | class TextMatch(object): 5 | 6 | """ 7 | Provides a suite of text matching methods 8 | """ 9 | 10 | @classmethod 11 | def dict_call(cls, test, text, expression): 12 | """ 13 | Allows test methods to be called easily from variables 14 | """ 15 | return { 16 | 'equals': cls.equals, 17 | 'startswith': cls.startswith, 18 | 'endswith': cls.endswith, 19 | 'contains': cls.contains, 20 | 're_search': cls.re_search 21 | }[test](text, expression) 22 | 23 | @staticmethod 24 | def equals(text, expression): 25 | """Text equivalence test""" 26 | return text == expression 27 | 28 | @staticmethod 29 | def startswith(text, expression): 30 | """Text starts with test""" 31 | return text.startswith(expression) 32 | 33 | @staticmethod 34 | def endswith(text, expression): 35 | """Text ends with test""" 36 | return text.endswith(expression) 37 | 38 | @staticmethod 39 | def contains(text, expression): 40 | """Text contains test""" 41 | return expression in text 42 | 43 | @staticmethod 44 | def re_search(text, expression): 45 | """ 46 | Test regex match. This method is comparatively 47 | very slow and should be avoided where possible. 48 | """ 49 | return re.search(expression, text) is not None 50 | --------------------------------------------------------------------------------