网络Python案例:把路由表提取出目标ip与下一跳到excel表格中
网络Python案例:把路由表提取出目标ip与下一跳到excel表格中

j6594-A1-huawei_ssh_log_2025_05_24_18_04_44.txt
源文件:

结果:

特点:
1、从txt提取路由表的目白ip与下一跳ip到excel表格中。
代码开始,如下:
#PyCharm 2023.3.3
#Python3.9.12
#Anaconda Navigator (Anaconda3)
# 使用说明:
#
# 使用说明:
#
# 这段代码会读取router-all.txt文件,提取所有"display ip routing-table"命令和"RD"后的IP地址,然后将结果保存到router-summary.xlsx文件中6。代码使用了正则表达式进行模式匹配,并使用pandas库创建Excel表格3。
import re
import pandas as pd
from datetime import datetime
def parse_router_file(input_file):
ip_list = []
next_hop_list = []
with open(input_file, 'r') as f:
content = f.read()
# 匹配display ip routing-table后的IP地址
ip_pattern = r'display ip routing-table\s+(\d+\.\d+\.\d+\.\d+)'
ips = re.findall(ip_pattern, content)
# 匹配RD后的下一跳地址
rd_pattern = r'RD\s+(\d+\.\d+\.\d+\.\d+)'
next_hops = re.findall(rd_pattern, content)
# 确保两个列表长度相同
min_len = min(len(ips), len(next_hops))
ip_list = ips[:min_len]
next_hop_list = next_hops[:min_len]
return ip_list, next_hop_list
def save_to_excel(ip_list, next_hop_list):
# 生成带时间戳的文件名
timestamp = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
output_file = f"router_summary_{timestamp}.xlsx"
# 创建DataFrame
df = pd.DataFrame({
'Destination IP': ip_list,
'Next Hop': next_hop_list
})
# 保存到Excel
df.to_excel(output_file, index=False)
print(f"数据已保存到 {output_file}")
if __name__ == "__main__":
input_file = "router-all.txt"
ip_list, next_hop_list = parse_router_file(input_file)
save_to_excel(ip_list, next_hop_list)代码结束,如上。
1、本站资源长期持续更新。
2、本资源基本为原创,部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
3、本站大部分文章的截图来源实验测试环境,请不要在生产环境中随意模仿,以免带来灾难性后果。
转载请保留出处: www.zh-cjh.com珠海陈坚浩博客 » 网络Python案例:把路由表提取出目标ip与下一跳到excel表格中
2、本资源基本为原创,部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
3、本站大部分文章的截图来源实验测试环境,请不要在生产环境中随意模仿,以免带来灾难性后果。
转载请保留出处: www.zh-cjh.com珠海陈坚浩博客 » 网络Python案例:把路由表提取出目标ip与下一跳到excel表格中
作者: 小编
| 手机扫一扫,手机上查看此文章: |
一切源于价值!
其他 模板文件不存在: ./template/plugins/comment/pc/index.htm