gpt4 book ai didi

Python 在 Apache 日志文件中搜索 IP 数量

转载 作者:太空宇宙 更新时间:2023-11-04 08:56:15 25 4
gpt4 key购买 nike

我正在寻找 IP 地址在标准 apache 日志文件中弹出的次数,这是我目前所拥有的,但它总是给出零:

def ips_in_log(log_name):
with open(log_name, 'r') as f:
log = f.read()
ipcount = log.count(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
print(ipcount)

这是日志文件中的示例行:

137.43.92.119 - - [04/Feb/2013:00:00:00 +0000] "GET /node/feed 
HTTP/1.0" 200 47208 "-" "Mozilla/5.0 (X11; U; Linux i686; en-US;
rv:1.7) Gecko/20040803 Firefox/0.9.3"

最佳答案

你不能将正则表达式传递给 count 函数,因为 count 函数接受一个字符串作为参数并在你的文本中查找它,当你传递 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' 它假定它是一行字符串。

相反,您可以使用 re.findall 查找所有匹配项,然后使用 len 函数获取 ip 的计数:

编辑:同时删除正则表达式尾部的 anchor $

def ips_in_log(log_name):
with open(log_name, 'r') as f:
log = f.read()
ipcount = len(re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',log))
print(ipcount)

如果您只想要长度作为替代方式,您可以使用 finditer返回一个产生 MatchObject 实例的迭代器。

def ips_in_log(log_name):
with open(log_name, 'r') as f:
log = f.read()
ipcount = sum(1 for _ in re.finditer(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',log))
print(ipcount)

关于Python 在 Apache 日志文件中搜索 IP 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29924416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com