我正在使用一个SIEM,需要能够从相对较大的文件解析IP地址。它们没有一致的字段,因此“剪切”不是一个选项。我正在使用一个修改过的python脚本来删除除a-z a-z 0-9和句点“.”之外的所有字符,以便可以正确地分析该文件。问题是这不适用于我的SIEM文件。如果我有一个像这样的文本文件“192.168.1.2!@#$!@%@$“很好,它将正确地删除所有我不需要的字符,并将IP输出到一个新文件。问题是,如果文件看起来是这样的“192.168.168.168@#$%this is a test”,则在删除异常字符的第一阶段之后,它将不受影响。请帮忙,我不知道它为什么这样做。这是我的代码:

    #!/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本身:
regex = re.findall(r'(?:\d{1,3}\.){3}\d{1,3}', text)

09-04 12:28
查看更多