【问题标题】:Python search logs using wildcard options使用通配符选项的 Python 搜索日志
【发布时间】:2020-06-20 12:15:37
【问题描述】:

我有一个非常大的 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)

【问题讨论】:

    标签: python search python-re


    【解决方案1】:

    您拥有的违规站点不是正则表达式,它们是外壳通配符。但是,您可以使用 fnmatch.translate 将它们转换为正则表达式:

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

    【讨论】:

      【解决方案2】:

      您也可以使用fnmatch.fnmatch() 进行通配符模式搜索。

      演示:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-06
        • 2017-09-16
        • 1970-01-01
        • 2020-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-27
        相关资源
        最近更新 更多