到目前为止,程序接收目录中的所有文本文件,然后将它们输出到名称相同的文件但是.out。如果有一个IP地址1992.168.1.1-192.168.1.7
,我希望它将该范围内的所有ips输出到新文件名。
#!/usr/bin/env python
import sys
import re
import os
try:
if file.endswith (".txt"):
f=open(file, 'r')
try:
file = open(f, "r")
ips = []
for text in file.readlines():
regex = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',text)
if regex is not None and regex not in ips:
ips.append(regex)
for ip in ips:
#name of the file
name = os.path.splitext() [0]
name = name +".out"
outfile = open(name, 'w')
spider = "".join(ip)
if spider is not '':
outfile.write(spider)
outfile.write("\n")
finally:
file.close()
outfile.close()
except IOError, (errno, strerror):
print "I/O Error(%s) : %s" % (errno, strerror)
答案 0 :(得分:1)
如果您使用的是Python 3.3+,请使用ipaddress模块:
>>> for addr in IPv4Network('192.0.2.0/28'):
... addr
...
IPv4Address('192.0.2.0')
IPv4Address('192.0.2.1')
IPv4Address('192.0.2.2')
IPv4Address('192.0.2.3')
IPv4Address('192.0.2.4')
IPv4Address('192.0.2.5')
IPv4Address('192.0.2.6')
...
IPv4Address('192.0.2.15')
答案 1 :(得分:0)
可能最简单的方法是将ip解析成一个整数 - 如果你想自己滚动,那就是。
def ip_to_int(ipstr):
b = [ int(p) for p in ipstr.split('.') ]
return (b[0] << 24) + (b[1] << 16) + (b[2] << 8) + b[3]
def int_to_ip(i):
octets = []
for n in range(4):
octets.append(i & 0xff)
i >>= 8
return ".".join([ str(octet) for octet in octets[::-1]])
def iprange(ipstring):
ipstart, ipend = ipstring.split('-')
return [ int_to_ip(ipint) for ipint in range(ip_to_int(ipstart), ip_to_int(ipend)+1) ]
这实际上并不了解有效地址(网络地址),也没有任何错误检查。