温馨提示×

怎样用脚本处理apache日志

小樊
35
2026-09-16 10:54:02
栏目: 编程语言

处理 Apache 日志通常会用到 shell 脚本 + awk / sed / grep,或者直接上 Python / Go 做更复杂的分析。下面按“常见需求 + 示例脚本”来讲。


一、先认识 Apache 日志格式

常见的是 combined 格式

127.0.0.1 - - [10/Oct/2024:13:55:36 +0800] "GET /index.html HTTP/1.1" 200 2326 "https://example.com" "Mozilla/5.0"

字段含义:

  1. IP
  2. 客户端标识(-)
  3. 用户(-)
  4. 时间
  5. 请求方法 + URL + 协议
  6. 状态码
  7. 响应大小
  8. Referer
  9. User-Agent

二、Shell 脚本常见处理示例

1️⃣ 统计访问最多的 IP(Top 10)

awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10

脚本封装:

#!/bin/bash
LOG=$1
awk '{print $1}' "$LOG" | sort | uniq -c | sort -rn | head -10

2️⃣ 统计状态码分布

awk '{print $9}' access.log | sort | uniq -c | sort -rn

3️⃣ 查看 404 请求

awk '$9 == 404 {print $1, $7}' access.log

4️⃣ 统计某个 URL 的访问次数

awk '$7 == "/login" {count++} END {print count}' access.log

5️⃣ 按小时统计访问量

awk '{print substr($4, 2, 14)}' access.log | sort | uniq -c

输出示例:

100 10/Oct/2024:13
120 10/Oct/2024:14

三、用 Python 处理(更灵活)

示例:用 Python 统计 IP 和状态码

from collections import Counter

ip_counter = Counter()
status_counter = Counter()

with open("access.log") as f:
    for line in f:
        parts = line.split()
        if len(parts) < 9:
            continue
        ip = parts[0]
        status = parts[8]
        ip_counter[ip] += 1
        status_counter[status] += 1

print("Top IPs:")
for ip, count in ip_counter.most_common(10):
    print(ip, count)

print("Status:")
for s, c in status_counter.items():
    print(s, c)

四、进阶:用 logrotate + 脚本自动化

/etc/logrotate.d/apache2
/var/log/apache2/access.log {
    daily
    rotate 30
    missingok
    notifempty
    compress
    postrotate
        /usr/bin/python3 /opt/scripts/analyze_log.py
    endscript
}

五、常见分析方向建议

  • ✅ 异常 IP(暴力破解、爬虫)
  • ✅ 慢请求(结合 %D 响应时间)
  • ✅ 爬虫识别(User-Agent)
  • ✅ 安全审计(404 / 500 暴增)

如果你有具体需求(比如“我想统计某个接口的平均响应时间”或“找出攻击 IP”),可以直接告诉我,我给你写完整脚本。

0