(Python)用于从Cisco配置中提取网络对象组的Regex

wgmfuz8q  于 2023-01-21  发布在  Python
关注(0)|答案(1)|浏览(120)

我想使用Python和正则表达式从Cisco配置中提取网络组。该组以object-group network Cloudflare开头,紧接着是一个或多个类似network-object 173.245.48.0 255.255.240.0的子网。文本如下所示

object-group network Cloudflare
 network-object 173.245.48.0 255.255.240.0
 network-object 103.21.244.0 255.255.252.0
 network-object 103.22.200.0 255.255.252.0
 network-object 103.31.4.0 255.255.252.0
 network-object 141.101.64.0 255.255.192.0
 network-object 108.162.192.0 255.255.192.0
 network-object 190.93.240.0 255.255.240.0
 network-object 188.114.96.0 255.255.240.0
 network-object 197.234.240.0 255.255.252.0
 network-object 198.41.128.0 255.255.128.0
 network-object 162.158.0.0 255.254.0.0
 network-object 104.16.0.0 255.248.0.0
 network-object 104.24.0.0 255.252.0.0
 network-object 172.64.0.0 255.248.0.0
 network-object 131.0.72.0 255.255.252.0

当使用这个正则表达式(?P<name>object-group network Cloudflare)\n(?P<subnets> network-object \d+\.\d+\.\d+\.\d+ \d+\.\d+\.\d+\.\d+\n)*时,我得到了3个匹配组,其中只有第一个是可用的,但它包含头部object-group ...。可以改进吗?https://regex101.com/r/s925cq/1

mwkjh3gx

mwkjh3gx1#

data = """
 network-object 1.1.1.1 0.0.0.0
object-group network Cloudflare
 network-object 173.245.48.0 255.255.240.0
 network-object 103.21.244.0 255.255.252.0
 network-object 103.22.200.0 255.255.252.0
 network-object 103.31.4.0 255.255.252.0
 network-object 141.101.64.0 255.255.192.0
 network-object 108.162.192.0 255.255.192.0
 network-object 190.93.240.0 255.255.240.0
 network-object 188.114.96.0 255.255.240.0
 network-object 197.234.240.0 255.255.252.0
 network-object 198.41.128.0 255.255.128.0
 network-object 162.158.0.0 255.254.0.0
 network-object 104.16.0.0 255.248.0.0
 network-object 104.24.0.0 255.252.0.0
 network-object 172.64.0.0 255.248.0.0
 network-object 131.0.72.0 255.255.252.0
access-list outside
"""

regex=r"object-group network (?P<network>\S+)|network-object\s(?P<subnet>\S+?)\s(?P<mask>\S+)"
matches = re.finditer(regex, data)
result = []
network_group = {"network": "Unknown"}

for cnt, match in enumerate(matches):
    info = match.groupdict()
    info1 = {k: v for k, v in info.items() if v is not None}
    if check:=info.get("network"):
        network_group =   {"network": check} if check else network_group
    if not info.get("network"):
        result.append(network_group | info1)
result

相关问题