我正在使用 SIEM,需要能够从相对较大的文件中解析 IP 地址。它们没有一致的字段,因此“剪切”不是一个选项。我正在使用修改后的 python 脚本来删除除 a-z A-Z 0-9 和句点“.”之外的所有字符。以便可以正确解析该文件。问题是这不适用于我的 SIEM 文件。如果我有一个看起来像这样的文本文件“192.168.1.2!@#$!@%@$”,那很好,它会正确删除我不需要的所有字符,并仅将 IP 输出到新文件。问题是,如果文件看起来像这样“192.168.168.168@#$% 这是一个测试”,那么在删除异常字符的第一阶段之后,它就会不管它。请帮忙,我不知道为什么会这样。这是我的代码:
#!/usr/bin/python
import re
import sys
unmodded = raw_input("Please enter the file to parse. Example: /home/aaron/ipcheck: ")
string = open(unmodded).read()
new_str = re.sub('[^a-zA-Z0-9.\n\.]', ' ', string)
open('modifiedipcheck.txt', 'w').write(new_str)
try:
file = open('modifiedipcheck.txt', "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("checkips", "a")
combine = "".join(ip)
if combine is not '':
print "IP: %s" % (combine)
outfile.write(combine)
outfile.write("\n")
finally:
file.close()
outfile.close()
大家有什么想法吗?预先非常感谢。
最佳答案
您的正则表达式以 $
结尾,这表明它希望该行在该点结束。如果删除它,它应该可以正常工作:
regex = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', text)
您还可以进一步简化正则表达式本身:
regex = re.findall(r'(?:\d{1,3}\.){3}\d{1,3}', text)
关于Python IP解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15131492/