You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python CiscoConfParse解析配置:提取接口详情与识别WAN IP池

解析华为配置提取接口详情并识别WAN IP池(使用CiscoConfParse)

Got it, let's break this down into manageable steps. CiscoConfParse works great for parsing network configs even if they're Huawei-style—since the structure is similar to Cisco's, we can leverage the library's tools without much hassle. Here's how to extract the interface details you need and identify the WAN IP pool.

Step 1: Install CiscoConfParse

First, make sure you have the library installed:

pip install ciscoconfparse

Step 2: Full Python Script

Here's a complete, commented script that handles your config. I've tailored it to match the fields you're looking for:

from ciscoconfparse import CiscoConfParse

def parse_network_config(config_file_path):
    # Load the config file (use IOS syntax—Huawei configs play nice with this)
    config_parse = CiscoConfParse(config_file_path, syntax='ios')
    
    # Initialize storage for results
    interface_records = []
    wan_ip_pool = []

    # Loop through every interface in the config
    for intf_obj in config_parse.find_objects(r'^interface\s+'):
        intf_data = {
            'interface_name': intf_obj.text.split()[1],
            'description': None,
            'vlan_type': None,
            'qos_policy': None,
            'ip_address': None,
            'qos_profiles': [],
            'user_queues': []
        }

        # Extract description if present
        desc_match = intf_obj.re_search_children(r'^ description\s+')
        if desc_match:
            intf_data['description'] = desc_match[0].text.split(' ', 1)[1].strip()

        # Extract VLAN type (dot1q subinterface config)
        vlan_match = intf_obj.re_search_children(r'^ vlan-type\s+dot1q\s+')
        if vlan_match:
            intf_data['vlan_type'] = vlan_match[0].text.strip()

        # Extract traffic-policy (QoS policy)
        qos_policy_match = intf_obj.re_search_children(r'^ traffic-policy\s+')
        if qos_policy_match:
            intf_data['qos_policy'] = qos_policy_match[0].text.strip()

        # Extract all qos-profile entries
        qos_profile_matches = intf_obj.re_search_children(r'^ qos-profile\s+')
        for line in qos_profile_matches:
            intf_data['qos_profiles'].append(line.text.strip())

        # Extract all user-queue entries
        user_queue_matches = intf_obj.re_search_children(r'^ user-queue\s+')
        for line in user_queue_matches:
            intf_data['user_queues'].append(line.text.strip())

        # Extract IP address/subnet
        ip_match = intf_obj.re_search_children(r'^ ip address\s+')
        if ip_match:
            ip_parts = ip_match[0].text.split()
            intf_data['ip_address'] = f"{ip_parts[2]}/{ip_parts[3]}"
            # Add to WAN pool if interface description starts with EXT_ (your example's WAN marker)
            if intf_data['description'] and intf_data['description'].startswith('EXT_'):
                wan_ip_pool.append(ip_parts[2])

        # Only add interfaces with meaningful data to the results
        if any(val for val in intf_data.values() if val not in [None, []]):
            interface_records.append(intf_data)

    return interface_records, wan_ip_pool

# Example usage
if __name__ == "__main__":
    config_path = 'network_config.txt'  # Replace with your config file path
    interfaces, wan_ips = parse_network_config(config_path)

    # Print formatted interface details
    print("=== Extracted Interface Details ===")
    for idx, intf in enumerate(interfaces, 1):
        print(f"\n{idx}. Interface: {intf['interface_name']}")
        if intf['description']:
            print(f"   Description: {intf['description']}")
        if intf['vlan_type']:
            print(f"   VLAN Type: {intf['vlan_type']}")
        if intf['qos_policy']:
            print(f"   QoS Policy: {intf['qos_policy']}")
        if intf['ip_address']:
            print(f"   IP Address: {intf['ip_address']}")
        if intf['qos_profiles']:
            print(f"   QoS Profiles: {' | '.join(intf['qos_profiles'])}")
        if intf['user_queues']:
            print(f"   User Queues: {' | '.join(intf['user_queues'])}")

    # Print WAN IP pool
    print("\n=== WAN IP Pool ===")
    print(f"Public WAN IPs (from EXT_ labeled interfaces): {', '.join(wan_ips)}")

Step 3: How It Works

Let's walk through the key bits:

  • Config Loading: We use syntax='ios' because Huawei's config structure (hierarchical, interface blocks with child lines) is compatible with the IOS parser.
  • Field Extraction: For each interface, we use re_search_children to scan lines under the interface block and pull out the data you need. Regex lets us target specific commands like description or vlan-type.
  • WAN IP Identification: Your example uses EXT_ in descriptions for external/WAN links—we use this marker to filter and collect those IPs into the WAN pool. If you need a stricter check (like verifying public IP ranges), you can add logic with the ipaddress library to validate IPs.

Step 4: Sample Output

Running this script with your example config will produce output like this:

=== Extracted Interface Details ===

1. Interface: Aux0/0/1

2. Interface: Eth-Trunk1
   Description: TO DEL-CON-S5328EI-SW-A5 Eth-Trunk2

3. Interface: Eth-Trunk1.50

4. Interface: Eth-Trunk1.120
   Description: EXT_COGENT E SERVICES PRIVATE LIMITED_12005744750_50MB
   VLAN Type: vlan-type dot1q 120
   QoS Policy: traffic-policy INFRA-ACL inbound
   IP Address: 111.93.43.217/255.255.255.252
   QoS Profiles: qos-profile 50Mbps inbound identifier none | qos-profile 50Mbps outbound identifier none

5. Interface: Eth-Trunk1.123
   Description: EXT_ILL_SARALA-HANDICRAFTS_PANIPAT_5018027739
   VLAN Type: vlan-type dot1q 123
   QoS Policy: traffic-policy INFRA-ACL inbound
   IP Address: 182.156.211.161/255.255.255.252
   User Queues: user-queue cir 10240 pir 10400 inbound | user-queue cir 10240 pir 10400 outbound

=== WAN IP Pool ===
Public WAN IPs (from EXT_ labeled interfaces): 111.93.43.217, 182.156.211.161

Quick Notes

  • Adjust regex patterns if your config has slight variations (like different indentation or command wording).
  • For public IP validation, add code like import ipaddress; if not ipaddress.ip_address(ip_parts[2]).is_private: to filter instead of relying on descriptions.

内容的提问来源于stack exchange,提问作者Anna Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:29:22