如何利用正则表达式扫描提取IP并生成指定格式的路由信息输出?
Great question! Instead of just extracting IP addresses in isolation, we can create a targeted regex pattern that captures all the required fields from each routing table line, then map those fields into a dictionary for easy use in your program. Here's how to do it step by step:
Step 1: Define a Regex Pattern to Capture All Fields
We need a regex that matches the structure of your routing table lines and extracts each component (protocol code, prefix, AD/metric, next-hop, update time, interface). The pattern below handles both single-code protocols (like D for EIGRP) and multi-part codes (like O E2 for OSPF External Type 2):
import re # Regex pattern to capture all required fields route_pattern = r'^(\w+)(?:\s+(\w+))?\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\s+\[([0-9]+/[0-9]+)\]\s+via\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+),\s+([0-9]+:[0-9]+:[0-9]+),\s+(\w+\d+)$'
Let's break down the pattern:
^(\w+)(?:\s+(\w+))?: Captures the protocol code (e.g.,DorO E2)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+): Captures the network prefix IP\[([0-9]+/[0-9]+)\]: Captures the AD/Metric value inside bracketsvia\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+): Captures the next-hop IP,\s+([0-9]+:[0-9]+:[0-9]+): Captures the last update time,\s+(\w+\d+)$: Captures the outbound interface
Step 2: Map Protocol Codes to Full Names
Create a dictionary to translate shorthand protocol codes to their full names (adjust this to include all protocols you need to handle):
protocol_mapping = { 'D': 'EIGRP', 'O': 'OSPF', 'O E2': 'OSPF External Type 2', # Add other protocol codes here as needed }
Step 3: Parse the Line and Build the Dictionary
Use the regex to match your target line, extract the captured groups, and populate your result dictionary:
# Example target line (the highlighted entry from your input) target_line = "D 10.67.10.0 [200/128] via 10.119.254.244, 0:02:22, Ethernet2" # Match the pattern against the line match = re.match(route_pattern, target_line) if match: # Extract captured groups proto_part1 = match.group(1) proto_part2 = match.group(2) prefix = match.group(3) ad_metric = match.group(4) next_hop = match.group(5) last_update = match.group(6) outbound_int = match.group(7) # Build the full protocol name proto_key = f"{proto_part1} {proto_part2}" if proto_part2 else proto_part1 protocol = protocol_mapping.get(proto_key, proto_key) # Fallback to code if no mapping exists # Create the final dictionary route_dict = { 'Protocol': protocol, 'Prefix': prefix, 'AD/Metric': ad_metric, 'Next-Hop': next_hop, 'Last Update': last_update, 'Outbound interface': outbound_int } # Print or use the dictionary in your program for key, value in route_dict.items(): print(f"{key}: {value}") else: print("No match found for the routing table line.")
Output
Running this code will produce exactly the format you need:
Protocol: EIGRP Prefix: 10.67.10.0 AD/Metric:200/128 Next-Hop:10.119.254.244 Last Update:0:02:22 Outbound interface: Ethernet2
Processing Multiple Lines
If you need to process all lines in your routing table, simply loop through each line and apply the same matching logic. This will build a list of route dictionaries that you can pass to other modules in your program.
内容的提问来源于stack exchange,提问作者Calvin Rider

