编程技术分享平台

网站首页 > 技术教程 正文

使用python的正则截取nginx日志中IP和agent

xnh888 2024-10-06 04:59:20 技术教程 21 ℃ 0 评论

老李问了我一个问题,nginx日志里如何去截取IP和agent,直接让他用awk截取对应的位数,但是agent的样式是"%E6%9E%3D%E8%A%81%E93%AE%99999D/6.0.3 CFNetwork/1485 Darwin/23.1.0" awk不太好处理。

以下是一段示例日志

# cat nginx.log
2024-01-10T10:18:02+08:00 112.162.57.58 - - [10/Jan/2024:10:18:02 +0800] "GET /tg*/monitor/monitor.* HTTP/1.1" 403 GET /tg*/monitor/monitor.* HTTP/1.1 382 146 "-" "%E6%8E%3C%E8%AF%81%E3%AE%9D/6.0.3 CFNetwork/1485 Darwin/23.1.0" "-" - - 0.000
2024-01-10T10:18:03+08:00 113.162.57.5 - - [10/Jan/2024:10:18:02 +0800] "GET /tg*/monitor/monitor.* HTTP/1.1" 403 GET /tg*/monitor/monitor.* HTTP/1.1 382 146 "-" "%E6%8E%8C%E3%AF%83%E5%AE%9D/6.0.3 CFNetwork/1485 Linux/23.1.0" "-" - - 0.000
2024-01-10T10:18:04+08:00 115.162.57.59 - - [10/Jan/2024:10:18:02 +0800] "GET /tgw*/monitor/monitor.* HTTP/1.1" 403 GET /tgw*/monitor/monitor.* HTTP/1.1 382 146 "-" "%E6%8E%83%E8%AF%381%E5%AE%9D/6.0.2 CFNetwork/1485 Darwin/23.1.1" "-" - - 0.000

可以使用python的正则来处理,以下是一段示例代码参考(GPT来的,我不会写):

import re

# 打开并逐行读取日志文件
with open('nginx.log', 'r') as file:
    for line in file:
        # 提取IP
        ip = re.findall(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b', line)[0]
        
        # 提取代理信息(这里假设日志格式保持一致,最后一个双引号内的内容是Agent)
        agent = re.findall(r'"([^"]*)"', line)[-2]

        print("IP:", ip , "Agent:", agent)

执行效果如下:

脚本发给老李,然后就没有然后了,估计是老李觉得这个不好用吧。。。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表