Python Forum

Full Version: CiscoConfParse to json output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

I am trying to capture Interface,Description, Vlan,IP address,Subnet mark from huawei router configuration file.

"""
example script how to extract parameters from a Cisco IOS configuration using ciscoconfparse
"""
import json
from ciscoconfparse import CiscoConfParse
from ciscoconfparse.ccp_util import IPv4Obj

if __name__ == "__main__":
    # the result dictionary
    result = {
        "features": [],
        "interfaces": {}
    }

    confparse = CiscoConfParse("huwaieconf.txt")

    interface_cmds = confparse.find_objects(r"^interface ")

    # iterate over the resulting IOSCfgLine objects
    for interface_cmd in interface_cmds:
        # get the interface name (remove the interface command from the configuration line)
        intf_name = interface_cmd.text[len("interface "):]
        result["interfaces"][intf_name] = {}

        # search for the description command, if not set use "not set" as value
        result["interfaces"][intf_name]["description"] = "not set"
        for cmd in interface_cmd.re_search_children(r"^ description "):
            result["interfaces"][intf_name]["description"] = cmd.text.strip()[len("description "):]

        result["interfaces"][intf_name]["qos-profile"] = "n/a"
        for cmd in interface_cmd.re_search_children(r"^ qos-profile "):
            result["interfaces"][intf_name]["qos-profile"] = cmd.text.strip()[len("qos-profile"):]
        result["interfaces"][intf_name]["vlan-type"] = "n/a"
        for cmd in interface_cmd.re_search_children(r"^ vlan-type "):
            result["interfaces"][intf_name]["vlan-type"]  = cmd.text.strip()[len("vlan-type"):]

        IPv4_REGEX = r"ip\saddress\s(\S+\s+\S+)"

        for cmd in interface_cmd.re_search_children(IPv4_REGEX):
            # ciscoconfparse provides a helper function for this task
            ipv4_addr = interface_cmd.re_match_iter_typed(IPv4_REGEX, result_type=IPv4Obj)

            result["interfaces"][intf_name].update({
                  "address": ipv4_addr.ip.exploded,
                  "netmask": ipv4_addr.netmask.exploded,
                  "network": ipv4_addr.network.exploded
            })

    print("\nEXTRACTED PARAMETERS\n")
    print(json.dumps(result, indent=4))
    data = json.dumps(result, indent=4)
    s = json.dumps(data)
    open("out.json","w").write(s)
sample output as below

Output:
EXTRACTED PARAMETERS { "features": [], "interfaces": { "Aux0/0/1": { "description": "not set", "qos-profile": "n/a", "vlan-type": "n/a" }, "Eth-Trunk1": { "description": "TO DEL-CON-S5328EI-SW-A5 Eth-Trunk2", "qos-profile": "n/a", "vlan-type": "n/a" }, "Eth-Trunk1.50": { "description": "not set", "qos-profile": "n/a", "vlan-type": "n/a" }, "Eth-Trunk1.103": { "description": "EXT_ILL_TTSL_Bhopal_5075509146", "qos-profile": " 6Mb outbound identifier none", "vlan-type": " dot1q 103", "address": "111.93.33.9", "netmask": "255.255.255.252", "network": "111.93.33.8/30" }, "Eth-Trunk1.120": { "description": "EXT_COGENT E SERVICES PRIVATE LIMITED_12005744750_50MB", "qos-profile": " 50Mbps outbound identifier none", "vlan-type": " dot1q 120", "address": "111.93.43.217", "netmask": "255.255.255.252", "network": "111.93.43.216/30" }, } }
my issue is, if interface is not having ip address, output should be printed as

"Eth-Trunk1.120": {
"description": "EXT_COGENT E SERVICES PRIVATE LIMITED_12005744750_50MB",
"qos-profile": " 50Mbps outbound identifier none",
"vlan-type": " dot1q 120",
"address": "n/a",
"netmask": "n/a",
"network": "na"
You need to insert some initialization of your dict before loop in line # 39:
The code should look like the following:

# ....
result["interfaces"][intf_name].update({
                  "address": "n/a",
                  "netmask": "n/a",
                  "network": "n/a"
            })

for cmd in interface_cmd.re_search_children(IPv4_REGEX):
            # ciscoconfparse provides a helper function for this task
            ipv4_addr = interface_cmd.re_match_iter_typed(IPv4_REGEX, result_type=IPv4Obj)
 
            result["interfaces"][intf_name].update({
                  "address": ipv4_addr.ip.exploded,
                  "netmask": ipv4_addr.netmask.exploded,
                  "network": ipv4_addr.network.exploded
            })
# ...
thanks, will try and let you know.
why this printing on screen json format, however file dumps is not working.
dumping code

data = json.dumps(result, indent=4)
    s = json.dumps(data)
    open("out.json","w").write(s)
sample output

Output:
"{\n \"interfaces\": {\n \"Aux0/0/1\": {\n \"description\": \"not set\",\n \"qos-profile\": \"n/a\",\n \"vlan-type\": \"n/a\"\n },\n \"Eth-Trunk1\": {\n \"description\": \"TO DEL-CON-S5328EI-SW-A5 Eth-Trunk2\",\n \"qos-profile\": \"n/a\",\n \"vlan-type\": \"n/a\"\n },\n \"Eth-Trunk1.50\": {\n \"description\": \"not set\",\n \"qos-profile\": \"n/a\",\n \"vlan-type\": \"n/a\"\n },\n \"Eth-Trunk1.103\": {\n \"description\": \"EXT_ILL_TTSL_Bhopal_5075509146\",\n \"qos-profile\": \" 6Mb outbound identifier none\",\n \"vlan-type\": \" dot1q 103\",\n \"address\": \"111.93.33.9\",\n \"netmask\": \"255.255.255.252\",\n \"network\": \"111.93.33.8/30\"\n },\n \"Eth-Trunk1.120\": {\n \"description\": \"EXT_COGENT E SERVICES PRIVATE LIMITED_12005744750_50MB\",\n \"qos-profile\": \" 50Mbps outbound identifier none\",\n \"vlan-type\": \" dot1q 120\",\n \"address\": \"111.93.43.217\",\n \"netmask\": \"255.255.255.252\",\n \"network\": \"111.93.43.216/30\"\n },\n \"Eth-Trunk1.123\": {\n \"description\": \"EXT_ILL_SARALA-HANDICRAFTS_PANIPAT_5018027739\",\n \"qos-profile\": \"n/a\",\n \"vlan-type\": \" dot1q 123\",\n \"address\": \"182.156.211.161\",\n \"netmask\": \"255.255.255.252\",\n \"network\": \"182.156.211.160/30\"\n },\n \"Eth-Trunk1.128\": {\n \"description\": \"EXT_LIVEDIGITAL MARKETING SOLUTION PRIVATE LIMITED_12005725741\",\n \"qos-profile\": \" 4Mb outbound identifier none\",\n \"vlan-type\": \" dot1q 128\",\n \"address\": \"111.93.127.81\",\n \"netmask\": \"255.255.255.248\",\n \"network\": \"111.93.127.80/29\"\n },\n \"Eth-Trunk1.130\": {\n \"description\": \"EXT_MISUMI INDIA PVT LTD_12405738282\",\n \"qos-profile\": \" 30Mb outbound identifier none\",\n \"vlan-type\": \" dot1q 130\",\n \"address\": \"111.93.33.201\",\n \"netmask\": \"255.255.255.248\",\n \"network\": \"111.93.33.200/29\"\n },\n \"Eth-Trunk1.155\": {\n \"description\": \"EXT_IREO-12405068279\",\n \"qos-profile\": \" Internet_8Mb outbound identifier none\",\n \"vlan-type\": \" dot1q 155\",\n \"address\": \"111.93.232.221\",\n \"netmask\": \"255.255.255.252\",\n \"network\": \"111.93.232.220/30\"\n },\n \"Eth-Trunk1.157\": {\n \"description\": \"not set\",\n \"qos-profile\": \"n/a\",\n \"vlan-type\": \"n/a\"\n },\n \"Eth-Trunk1.158\": {\n \"description\": \"EXT_MATHWORKS INDIA PRIVATE LIMITED_1105725697\",\n \"qos-profile\": \" 10Mb outbound identifier none\",\n \"vlan-type\": \" dot1q 158\",\n \"address\": \"111.93.206.33\",\n \"netmask\": \"255.255.255.252\",\n \"network\": \"111.93.206.32/30\"\n },\n \"Eth-Trunk1.168\": {\n \"description\": \"not set\",\n \"qos-profile\": \"n/a\",\n \"vlan-type\": \"n/a\"\n },\n \"Eth-Trunk1.170\": {\n \"description\": \"EXT_NATIONAL HIGHWAYS AND INFRASTRUCTURE DEVE CORP LTD_1105722482\",\n \"qos-profile\": \"n/a\",\n \"vlan-type\": \" dot1q 170\",\n \"address\": \"111.93.193.141\",\n \"netmask\": \"255.255.255.252\",\n \"network\": \"111.93.193.140/30\"\n },\n
with open("out.json", "w") as f:
    f.write(json.dumps(result, indent=4))
thanks, its working
tried another code as i am not able to parser json data.

from ciscoconfparse import CiscoConfParse
from ciscoconfparse.ccp_util import IPv4Obj
import re
import ipaddress
result = {
        "interfaces": {}
        }

#interfaces = {}
confparse = CiscoConfParse("huwaietest.conf")
INTF_RE = re.compile(r'^interface\s\S+')
ADDR_RE = re.compile(r'ip\saddress\s(\S+\s+\S+)')
DESC_RE = re.compile(r'description ')
VLAN_TYPE = re.compile(r'vlan-type')
QOS_PROFILE = re.compile(r'qos-profile')
interface_cmds = confparse.find_objects(r"^interface ")
for interface_cmd in interface_cmds:
    # get the interface name (remove the interface command from the configuration line)
    intf_name = interface_cmd.text[len("interface "):]
    result["interfaces"][intf_name] = {}
    # if no vlan .. update as "not set"
    result["interfaces"][intf_name]["vlan_type"] = "not set"
    for vlan in interface_cmd.re_search_children(r"^ vlan-type"):
             result["interfaces"][intf_name]["vlan_type"] = vlan.text.strip()[len("vlan-type dot1q "):].split(' ')[0]
             # if no decrition... update as "not set"
             result["interfaces"][intf_name]["description"] = "not set"
             for descr in interface_cmd.re_search_children(r"^ description "):
                 result["interfaces"][intf_name]["description"] = descr.text.strip()[len("description "):]
                 result["interfaces"][intf_name]["ipv4"] = "not set"
                 #result["interfaces"][intf_name].update({"ipv4": "not set"})
                 IPv4_REGEX = r"ip\saddress\s(\S+\s+\S+)"
                 for ipv4_addr in interface_cmd.re_search_children(IPv4_REGEX):
                     ipv4_addr = interface_cmd.re_match_iter_typed(IPv4_REGEX, result_type=IPv4Obj)
                     result["interfaces"][intf_name]["ipv4"]= ipv4_addr.network.exploded
                     result["interfaces"][intf_name]["qos_profile"] = "not set"
                     for qos in interface_cmd.re_search_children(r"^ qos-profile"):
                         result["interfaces"][intf_name]["qos_profile"] = qos.text.strip()[len("qos-profile "):].split(' ')[0]
print(result["interfaces"])
Output:
{'Eth-Trunk5': {'vlan_type': 'not set'}, 'Eth-Trunk6': {'vlan_type': 'not set'}, 'Eth-Trunk6.1000': {'vlan_type': '1000', 'description': 'connecting to DEL-CON-S6348F-SW-A5_XG0/0/22', 'ipv4': '10.117.138.24/30', 'qos_profile': 'not set'}, 'Eth-Trunk6.1069': {'vlan_type': 'not set'}, 'Eth-Trunk6.1163': {'vlan_type': '1163', 'description': 'description EXT/ILL/791445/NEXTRA TELESERVICES PRIVATE LIMITE/12405742920/3.1Gbps/P2P', 'ipv4': '111.93.126.148/30', 'qos_profile': '3100Mbps'}, 'Eth-Trunk6.1164': {'vlan_type': '1164', 'description': 'EXT/ILL/828320/WI-BRO SOLUTIONS PRIVATE LIMITED/1105828320/NEW DELHI/1000MB/P2M/3333', 'ipv4': '14.98.85.112/30', 'qos_profile': '1000Mbps'}, 'Virtual-Template0': {'vlan_type': 'not set'}, 'GigabitEthernet0/0/0': {'vlan_type': 'not set'}, 'GigabitEthernet1/0/0': {'vlan_type': 'not set'}, 'GigabitEthernet1/0/1': {'vlan_type': 'not set'}, 'GigabitEthernet1/0/2': {'vlan_type': 'not set'}, 'GigabitEthernet1/0/2.511': {'vlan_type': '511', 'description': 'forUBR_NMS-Spoke location', 'ipv4': '10.117.137.192/30', 'qos_profile': 'not set'}, 'GigabitEthernet1/0/2.705': {'vlan_type': '705', 'description': 'GOOGLE_PERING_DELHI_VSB_IGW_A3', 'ipv4': '192.168.237.192/30', 'qos_profile': 'not set'}, 'GigabitEthernet1/0/3': {'vlan_type': 'not set'}, 'GigabitEthernet1/0/4': {'vlan_type': 'not set'}, 'GigabitEthernet3/0/0': {'vlan_type': 'not set'}, 'GigabitEthernet3/0/1': {'vlan_type': 'not set'}, 'GigabitEthernet3/0/2': {'vlan_type': 'not set'}, 'GigabitEthernet3/0/3': {'vlan_type': 'not set'}, 'GigabitEthernet3/0/4': {'vlan_type': 'not set'}}
not able to print in required format. Please help