Python IP解析

标签 python parsing ip

我正在使用 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/

相关文章:

python - 使用 scipy.integrate.quad 积分复数

parsing - 是什么让 Ometa 与众不同?

google-cloud-platform - 如何更改外部临时 ip

iphone - 如何从 iOS 上的主机名解析 IP 地址

Pythonic 方式在列表中查找重复映射,同时忽略某些键,然后组合重复映射以创建新列表

python - 部署许多不相关的 rest ml 模型

.net - 实现解析器的步骤和相关工作(在.Net中,在本例中为XPath 2.0)

kubernetes - kubectl : Unable to connect to the server : dial tcp 192. 168.214.136:6443:连接:主机没有路由

python - 使用 python 自动按下 "submit"按钮

parsing - 语言分析在现实生活中的应用?