用 python 中的主机地址替换网络地址

Replace network address with host address in python

我有一个 IP 地址为这种格式的文件

192.168.1.9

192.168.1.10

192.168.1.8

我读到了这样的列表

with open("file.txt") as f:
    ipaddr = f.read().splitlines()

然后运行一些功能。

不过,我也可以在本文档中输入网络地址,如 192.168.0.0/25 并以某种方式将它们翻译成

192.168.0.1

192.168.0.2

192.168.0.3

我什至不知道如何完成这个? (运行宁Python2.6)

您需要使用正则表达式解析您的文本文件。在 Python 中查找 're' 模块。这个想法的快速实现是:

import re
with open("ips.txt") as f:
    ip_raw_list = f.read().splitlines()

#Only takes the string after the '/'
reg_ex_1 = r'(?<=/)[0-9]*'
#Only take the first three numbers "0.0.0" of the IP address
reg_ex_2 = r'.*\..*\..*\.' 
ip_final_list = list()

for ip_raw in ip_raw_list:

    appendix = re.findall(reg_ex_1, ip_raw)

    #Ip with no backslash create on input
    if not appendix:
        ip_final_list.append(ip_raw)

    #Ip with backslash create several inputs

    else:

        for i in range(int(appendix[0])):
            ip_final_list.append(re.findall(reg_ex_2, ip_raw)[0] + str(i))

此代码使用正则表达式的功能将“0.0.0.0”形式的 IP 与“0.0.0.0/00”形式的 IP 分开。然后对于第一种形式的 IP,您将 IP 直接放在最终列表中。对于第二个 for 的 IP,您 运行 一个 for 循环将几个输入放入最终列表。

netaddr 是最好的方法之一:

import netaddr

with open('file.txt') as f:
    for line in f:
        try:
            ip_network = netaddr.IPNetwork(line.strip())
        except netaddr.AddrFormatError:
            # Not an IP address or subnet!
            continue
        else:
            for ip_addr in ip_network:
                print ip_addr

示例文件为:

10.0.0.1
192.168.0.230
192.168.1.0/29

它给出的输出是:

10.0.0.1
192.168.0.230
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7