[英]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
我什至不知道如何做到这一点? (运行Python 2.6)
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
您需要使用正则表达式解析文本文件。 在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循环将几个输入放入最终列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.