将单个 IP 地址组合到子网的脚本

问题描述 投票:0回答:1

我遇到了一个我自己无法解决的问题,即使在网上搜索也无法解决。 我有一个文本文件,其中包含约 30000 个单独的 IP 地址和子网。 通过查看该文件,我可以看出有很多完整的 /24 和 /25 ip 一一枚举,例如:

x2.6x.121.0

x2.6x.121.1

x2.6x.121.2

x2.6x.121.3

...

x2.6x.121.255

并且已经有更大的区块了:

xx2.24.32.0/24

xx2.24.7.0/23

如何检查所有行,如果有完整的 /24 或 /25 (甚至 /23 /22 等),只需将 /24 或 /25 写入新文件? 我需要一个软件来提供此列表,但我不想列出 ~30k /32 我想如果可能的话将它们组合成更大的块,但我需要精确,所以如果其中缺少一个 IP一个块我无法组合它,我需要用 /32 将它们一一列出。

我尝试将在线搜索的不同代码组合在一起,甚至尝试使用人工智能对其进行增强,但有些东西无法正常工作。 (我的编程能力非常有限)

最新代码是这样的:

import ipaddress

def find_subnets(ip_list):
    subnets = {}
    for ip in ip_list:
        ip_obj = ipaddress.IPv4Address(ip)
        subnet = ipaddress.IPv4Network(ip_obj.exploded + "/24", strict=False)
        if subnet in subnets:
            subnets[subnet].append(ip)
        else:
            subnets[subnet] = [ip]

    return subnets

def write_subnets_to_file(subnets, output_file):
    with open(output_file, "w") as f:
        for subnet, ips in subnets.items():
            if len(ips) == 256:
                f.write(f"{subnet}\n")
            else:
                for ip in ips:
                    f.write(f"{ip}/32\n")

def main(input_file, output_file):
    with open(input_file, "r") as f:
        ip_list = [line.strip() for line in f]

    subnets = find_subnets(ip_list)
    write_subnets_to_file(subnets, output_file)

if __name__ == "__main__":
    input_file = "input.txt"  # Replace with your input file name
    output_file = "output.txt"  # Replace with your output file name
    main(input_file, output_file)

但它仍然列出了很多/32,并且没有将它们合并到/24(尽管最后也有很多/24)。输入中甚至有 /23 和 /22,但输出中只有 /24。

python ip subnet
1个回答
0
投票

netaddr
包有一个
cidr_merge
功能
可以满足您的需求:

In [5]: from netaddr import cidr_merge

In [6]: cidr_merge(['10.0.0.0', '10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.4'])
Out[6]: [IPNetwork('10.0.0.0/30'), IPNetwork('10.0.0.4/32')]
© www.soinside.com 2019 - 2024. All rights reserved.