使用通配符选项的Python搜索日志

2024-05-20 04:38:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常大的netflow数据集,看起来像这样:

192.168.1.3  www.123.com
192.168.1.6  api.123.com
192.168.1.3  blah.123.com
192.168.1.3  www.google.com
192.168.1.6  www.xyz.com
192.168.1.6  test.xyz.com
192.168.1.3  3.xyz.co.uk
192.168.1.3  www.blahxyzblah.com
....

我还有一个更小的通配符域数据集,如下所示:

*.xyz.com
api.123.com
...

我希望能够使用python搜索我的数据集并找到所有匹配项。因此,在上面的示例中,我将匹配:

192.168.1.6  www.xyz.com
192.168.1.6  test.xyz.com
192.168.1.6  api.123.com

我试图使用re模块,但无法使其与任何内容匹配

for f in offendingsites:
    for l in logs:
        if re.search(f,l):
            print(l)

Tags: 数据intestrecom示例forwww
2条回答

您的违规站点不是正则表达式,而是shell通配符。但是,可以使用^{}将它们转换为正则表达式:

for f in offendingsites:
    r = fnmatch.translate(f)
    for l in logs:
        if re.search(r, l):
            print(l)

您还可以使用^{}进行通配符模式搜索

演示:

from fnmatch import fnmatch

with open("wildcards.txt") as offendingsites, open("dataset.txt") as logs:
    for f in offendingsites:
        for l in logs:
            f, l = f.strip(), l.strip() # Remove whitespace
            if fnmatch(l, f):
                print(l)

输出:

192.168.1.6  www.xyz.com
192.168.1.6  test.xyz.com

相关问题 更多 >