攻防演练,作为蓝方,分析nginx日志,统计访问为200的请求路径及其次数

发布于:2024-04-21 ⋅ 阅读:(202) ⋅ 点赞:(0)

请求结果为状态码 200 的日志条目。这需要调整正则表达式来捕获状态码,并基于此值进行过滤。

以下是更新后的脚本:

import re

def parse_log_file(file_path, output_file_path):
    # 正则表达式,用于匹配日志条目中的请求URL部分和状态码
    pattern = re.compile(r'\"GET\s(.*?)\sHTTP/\d\.\d\"\s(200)\s')

    # 字典,用于存储路径计数
    path_counts = {}

    with open(file_path, 'r') as file:
        for line in file:
            match = pattern.search(line)
            if match:
                url = match.group(1)
                # 分割URL以获取路径部分,限制到最多4个段
                path_parts = url.split('?')[0].split('/')
                # 仅考虑最多4个段的路径
                filtered_path = '/'.join(path_parts[:5])
                if filtered_path in path_counts:
                    path_counts[filtered_path] += 1
                else:
                    path_counts[filtered_path] = 1

    # 将结果写入输出文件
    with open(output_file_path, 'w') as output_file:
        for path, count in sorted(path_counts.items(), key=lambda item: item[1], reverse=True):
            output_file.write(f"{path}: {count}\n")

# 日志文件路径
log_file_path = '/mnt/data/nginx_logs.txt'
output_file_path = '/mnt/data/print.txt'

# 解析日志文件并写入输出
parse_log_file(log_file_path, output_file_path)

变更内容:

  1. 正则表达式调整:模式现在捕获特定返回 200 状态码的 GET 请求。
  2. 过滤逻辑:脚本检查捕获的状态码为 ‘200’ 后,再处理 URL 以计算路径计数。

确保日志文件 nginx_logs.txt 已上传到 /mnt/data/ 目录中,以便脚本可以找到并处理它。这个脚本将其结果输出到同一目录下的 print.txt 中,提供了以 200 状态码结果的 GET 请求的路径计数排序。


网站公告

今日签到

点亮在社区的每一天
去签到