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

标签 python regex string

我正在寻找 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/

相关文章:

python - 从向量列表计算距离矩阵

python - 如何使用位于不同 NAT 上的套接字在 2 个 Python 程序之间进行通信?

c# - 识别时换行(数字+字符串)

regex - 更漂亮的自动 "correct"正则表达式转义正斜杠 `\`

Python提取动态文本格式的文本数据

python - matplotlib 中矩形数组的曲面图

python - Django 中的 CSRF 验证失败

regex - 用于查找字符串中 URL 的正则表达式

python - 用特定字符替换字符串中的索引范围 - Python

c# - 如何根据单词中的给定索引找到单词的开始和结束索引?