[英]Python search logs using wildcard options
我有一个非常大的 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)
您拥有的违规站点不是正则表达式,它们是 shell 通配符。 但是,您可以使用fnmatch.translate
将它们转换为正则表达式:
for f in offendingsites:
r = fnmatch.translate(f)
for l in logs:
if re.search(r, l):
print(l)
您还可以使用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)
Output:
192.168.1.6 www.xyz.com
192.168.1.6 test.xyz.com
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.