【问题标题】:How to get network/subnet and nexthop from a routing table txt如何从路由表 txt 中获取网络/子网和下一跳
【发布时间】:2021-07-08 02:31:08
【问题描述】:

下面是网络设备路由表:

destination         nexthop                 metric flags     interface       
0.0.0.0/0           192.168.86.1            10     A S       ethernet1/1
10.1.1.0/26         192.168.86.81           10     A S       ethernet1/1
1.1.1.1/32          192.168.86.191          0      A C       ethernet1/1

如何使用正则表达式匹配格式为网络/子网掩码的字符串(即本例中的0.0.0.0/0, 10.1.1.0/26, 1.1.1.1/32)? 我尝试了以下。它不起作用:

import re
ip_with_mask = re.search(r'((2[0-5]|1[0-9]|[0-9])?[0-9]\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9])/(^[1-9]$|^[1-2][0-9]$|^3[0-2]$)', oneline).group()

((2[0-5]|1[0-9]|[0-9])?[0-9]\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9]) 是 IP 地址。 / 在网络和子网掩码之间。 ^[0-9]$|^[1-2][0-9]$|^3[0-2]$ 是 0-32 子网掩码号。

这个正则表达式有什么问题?

【问题讨论】:

  • 我不认为regex 是这里的正确选择。您希望实现什么目标?
  • 我想得到以下结果并保存到一个csv文件:0.0.0.0/0,192.168.86.1 10.1.1.0/26,192.168.86.81 1.1.1.1/32,192.168.86.191
  • 您如何检索数据?能否包含检索路由表的代码?
  • 我正在使用 netmiko SSH 连接到 Palo Alto VM 防火墙,执行“显示路由路由”。 connection = ConnectHandler(**device_dict) with open(routing-table.txt", 'w') as writefile: output = connection.send_command('show routing route') writefile.write(output) writefile.write('\n ') connection.disconnect()
  • 为什么在子网掩码定义中使用行尾$ 符号?

标签: python regex ip


【解决方案1】:

我不会在这里使用正则表达式。你有一个固定宽度的格式,那么为什么不尝试使用一个工具(例如 Python)来为你解析该格式?

试试这个:

import io
import pandas


# You can also read this from file, I'm using an in-memory file just for demo purposes
table = io.StringIO(
    """destination         nexthop                 metric flags     interface       
0.0.0.0/0           192.168.86.1            10     A S       ethernet1/1
10.1.1.0/26         192.168.86.81           10     A S       ethernet1/1
1.1.1.1/32          192.168.86.191          0      A C       ethernet1/1
"""
)

# Read a dataframe from a Fixed Width Format (fwf)
df: pandas.DataFrame = pandas.read_fwf(table)

# Show as CSV
print(df.to_csv(index=False))

输出:

destination,nexthop,metric,flags,interface
0.0.0.0/0,192.168.86.1,10,A S,ethernet1/1
10.1.1.0/26,192.168.86.81,10,A S,ethernet1/1
1.1.1.1/32,192.168.86.191,0,A C,ethernet1/1

【讨论】:

  • 太棒了!非常感谢您的帖子。
猜你喜欢
  • 2016-08-10
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2021-02-18
  • 1970-01-01
  • 2018-10-03
相关资源
最近更新 更多