| 1 |
"""ntc_templates.parse.""" |
| 2 |
import os |
| 3 |
|
| 4 |
# Due to TextFSM library issues on Windows, it is better to not fail on import |
| 5 |
# Instead fail at runtime (i.e. if method is actually used). |
| 6 |
try: |
| 7 |
from textfsm import clitable |
| 8 |
|
| 9 |
HAS_CLITABLE = True |
| 10 |
except ImportError: |
| 11 |
HAS_CLITABLE = False |
| 12 |
|
| 13 |
|
| 14 |
def _get_template_dir(): |
| 15 |
template_dir = os.environ.get("NTC_TEMPLATES_DIR") |
| 16 |
if template_dir is None: |
| 17 |
package_dir = os.path.dirname(__file__) |
| 18 |
template_dir = os.path.join(package_dir, "templates") |
| 19 |
if not os.path.isdir(template_dir): |
| 20 |
project_dir = os.path.dirname(os.path.dirname(os.path.dirname(template_dir))) |
| 21 |
template_dir = os.path.join(project_dir, "templates") |
| 22 |
|
| 23 |
return template_dir |
| 24 |
|
| 25 |
|
| 26 |
def _clitable_to_dict(cli_table): |
| 27 |
"""Convert TextFSM cli_table object to list of dictionaries.""" |
| 28 |
objs = [] |
| 29 |
for row in cli_table: |
| 30 |
temp_dict = {} |
| 31 |
for index, element in enumerate(row): |
| 32 |
temp_dict[cli_table.header[index].lower()] = element |
| 33 |
objs.append(temp_dict) |
| 34 |
|
| 35 |
return objs |
| 36 |
|
| 37 |
|
| 38 |
def parse_output(platform=None, command=None, data=None): |
| 39 |
"""Return the structured data based on the output from a network device.""" |
| 40 |
if not HAS_CLITABLE: |
| 41 |
msg = """ |
| 42 |
The TextFSM library is not currently supported on Windows. If you are NOT using Windows |
| 43 |
you should be able to 'pip install textfsm' to fix this issue. If you are using Windows |
| 44 |
then you will need to install the patch referenced here: |
| 45 |
|
| 46 |
https://github.com/google/textfsm/pull/82 |
| 47 |
|
| 48 |
""" |
| 49 |
raise ImportError(msg) |
| 50 |
|
| 51 |
template_dir = _get_template_dir() |
| 52 |
cli_table = clitable.CliTable("index", template_dir) |
| 53 |
|
| 54 |
attrs = {"Command": command, "Platform": platform} |
| 55 |
try: |
| 56 |
cli_table.ParseCmd(data, attrs) |
| 57 |
structured_data = _clitable_to_dict(cli_table) |
| 58 |
except clitable.CliTableError as err: |
| 59 |
raise Exception(f'Unable to parse command "{command}" on platform {platform} - {str(err)}') from err |
| 60 |
# Invalid or Missing template |
| 61 |
# module.fail_json(msg='parsing error', error=str(e)) |
| 62 |
# rather than fail, fallback to return raw text |
| 63 |
# structured_data = [data] |
| 64 |
|
| 65 |
return structured_data |