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

时间:2016-10-23 20:29:07

标签: python function ip-address

我有一个带有这种格式的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

我甚至不知道如何做到这一点? (运行Python 2.6)

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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&#39;”的IP。来自表格&#39; 0.0.0.0/00'的IP。然后,对于第一种形式的IP,您将IP直接放在最终列表中。对于第二个的IP,运行for循环以在最终列表中放入几个输入。