-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterface_parser.py
92 lines (76 loc) · 2.72 KB
/
interface_parser.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
from argparse import ArgumentParser
import csv
import logging
from ttp import ttp
from pprint import pprint
from pathlib import Path
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
script_path = Path(__file__).resolve().parent
ttp_interface_template = """
<group>
interface {{ interface }}
description {{ description | re(".*") }}
ip address {{ ipv4 }} {{ mask_v4 }}
shutdown {{ disabled | set(True) }}
mtu {{ mtu }}
encapsulation dot1Q {{ dot1q }}
encapsulation dot1q {{ dot1q }}
! {{ _end_ }}
</group>
"""
def get_inteface_params(config_data, template = ttp_interface_template):
# create parser object and parse data using template:
parser = ttp(data=config_data, template=template)
parser.parse()
all_interface_data = parser.result()[0][0]
pprint(all_interface_data)
# csv_results = parser.result(format='csv')[0]
# pprint(csv_results)
return all_interface_data
def main():
"""
summary:
"""
logging.basicConfig(level=logging.INFO,format= "%(asctime)s::%(name)s::-%(module)s::-: %(funcName)s - %(levelname)s :: - %(message)s")
# parse command line args
parser = ArgumentParser()
# positinal args ( Mandatory args)
parser.add_argument(
"input_config", type=str, help=" show run | sec interface "
)
# setting up logging to DEBUG level
parser.add_argument(
"--verbose",
"-v",
action="store_true",
help="set logging: DEBUG ",
)
# set logging to DEBUG based on CMD line args
cmd_args = parser.parse_args()
if cmd_args.verbose:
logger.setLevel(logging.DEBUG)
# set level for all handles
for hdler in logger.handlers:
hdler.setLevel(logging.DEBUG)
logger.debug("Loggig set to DEBUG")
logger.warning("Logging set to DEBUG")
input_config = cmd_args.input_config
with open(input_config,'r') as fp_config:
config_data = fp_config.read()
interface_data = get_inteface_params(config_data)
# use dict to csv writer
fieldnames = ["interface", "ipv4", "mask_v4","mtu", "description"]
with open('output.csv','w',newline='') as fp_out:
dict_writer = csv.DictWriter(fp_out, fieldnames=fieldnames,extrasaction='ignore')
dict_writer.writeheader()
for interface in interface_data:
if interface['interface'] == 'Loopback0':
pprint(interface)
dict_writer.writerow(interface)
elif interface.get("ipv4"):
pprint(interface)
dict_writer.writerow(interface)
if __name__ == "__main__":
main()