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

如何在元组列表中识别并展开CIDR地址块?

处理仓库IP白名单并导出CSV的解决方案

核心思路

遍历每个仓库的元组,拆分仓库名和所有IP/CIDR规则,将CIDR网段展开为单个IP,最终生成「仓库名-单个IP」的对应关系,导出为CSV文件。

完整实现代码

import ipaddress
import csv

# 你的原始元组列表
repo_ip_list = [
    ('Repo1', '192.168.90.0/24','192.168.1.10'),
    ('Repo2', '10.3.1.0/24'),
    ('Repo3', '10.2.11.0/24','10.12.127.0/24','10.57.3.0/24')
]

# 准备存储展开后的结果
expanded_data = []

for repo_tuple in repo_ip_list:
    repo_name = repo_tuple[0]
    # 提取元组中除仓库名外的所有IP/CIDR项
    ip_entries = repo_tuple[1:]
    
    for entry in ip_entries:
        try:
            # 处理CIDR网段或单个IP,strict=False允许单个IP(自动转为/32网段)
            network = ipaddress.ip_network(entry, strict=False)
            # 遍历网段内的所有IP,转为字符串存入结果
            for ip in network:
                expanded_data.append([repo_name, str(ip)])
        except ValueError:
            # 跳过无效的IP/CIDR(可选处理逻辑)
            print(f"跳过无效的IP/CIDR项:{entry}")

# 写入CSV文件
with open('repo_whitelist.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    # 写入表头
    writer.writerow(['仓库名', '允许上传的IP'])
    # 写入所有数据行
    writer.writerows(expanded_data)

关键细节说明

  • 处理单个IP与CIDR的兼容:使用ip_network(entry, strict=False),既可以解析192.168.90.0/24这类网段,也能兼容192.168.1.10这类单个IP(自动识别为/32网段)。
  • 错误处理:添加try-except捕获无效的IP/CIDR格式,避免程序崩溃。
  • CSV写入规范:使用newline=''防止Windows系统下出现空行,指定编码为utf-8保证兼容性。

内容的提问来源于stack exchange,提问作者Rudy Gee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:06:26