我有一个包含多个 IP 地址的文件。 4行txt大约有900个IP。我希望每行输出 1 个 IP。我怎样才能做到这一点?基于其他代码,我想出了这个,但它失败了,因为多个 IP 位于单行上:
import sys
import re
try:
if sys.argv[1:]:
print "File: %s" % (sys.argv[1])
logfile = sys.argv[1]
else:
logfile = raw_input("Please enter a log file to parse, e.g /var/log/secure: ")
try:
file = open(logfile, "r")
ips = []
for text in file.readlines():
text = text.rstrip()
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:
outfile = open("/tmp/list.txt", "a")
addy = "".join(ip)
if addy is not '':
print "IP: %s" % (addy)
outfile.write(addy)
outfile.write("\n")
finally:
file.close()
outfile.close()
except IOError, (errno, strerror):
print "I/O Error(%s) : %s" % (errno, strerror)
The $
表达式中的锚点会阻止您找到除最后一个条目之外的任何内容。删除它,然后使用返回的列表.findall()
:
found = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',text)
ips.extend(found)
re.findall()
将始终返回一个列表,该列表可能为空。
- 如果您只需要唯一的地址,请使用集合而不是列表。
- 如果您需要验证 IP 地址(包括忽略专用网络和本地地址),请考虑使用ipaddress.IPV4Address() class.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)