将IP范围和CIDR转换为十进制地址

时间:2016-12-07 22:00:10

标签: php python bash perl command-line

我的文件包含多种格式的多个IP地址。

以下是文件示例:

31.14.133.39
37.221.172.0/23
46.19.137.0/24
46.19.143.0/24
50.7.78.88/31
5.79.39.4,5.79.39.5
62.73.8.0/23
63.235.155.210
5.39.216.0,5.39.223.255
64.12.118.23
64.12.118.88

有些是CIDR格式,有些是范围,有些是单独的IP。

以下是3种不同的格式:

63.235.155.210
62.73.8.0/23
5.39.216.0,5.39.223.255

我想将所有行转换为IP小数范围。例如,上面列出的三格式样本如下所示:

1072405458,1072405458
1044973568,1044974079
86497280,86499327

该文件中有大约400,000行。

我可以通过命令行,Perl,Python或PHP来完成它。

1 个答案:

答案 0 :(得分:-1)

Python将在netaddr模块的帮助下为您完成此任务。

from netaddr import IPAddress, IPNetwork

with open("your file.txt", "r") as f:

    for line in f:

        if "/" in line:
            ip_network = IPNetwork(line)
            print "{},{}".format(
                ip_network.first,
                ip_network.last
            )
            continue

        if "," in line:
            first_ip, last_ip = line.split(",")
        else:
            first_ip = last_ip = line

        print "{},{}".format(
            int(IPAddress(first_ip)),
            int(IPAddress(last_ip))
        )

使用问题的三个示例输入和三个预期输出,上面的工作正常。

相关问题