Shell:nginx日志统计访问次数最多的IP
简单写法:
#!/bin/bash
# Nginx 日志文件路径
LOG_FILE="/path/to/your/nginx/access.log"
# 统计每个IP的访问次数,并按次数从大到小排序,只取第一条
awk '{print $1}' $LOG_FILE | sort | uniq -c | sort -nr | head -n 1
困难写法:
#!/bin/bash
# Nginx 日志文件路径
LOG_FILE="/path/to/your/nginx/access.log"
# 输出格式:日期、访问次数最多的IP、该IP的访问次数
awk '{print $1, substr($4, 2, 11)}' $LOG_FILE | # 提取 IP 和日期部分
awk '{count[$2" "$1]++} END { # 按 IP 和日期统计
for (key in count) {
split(key, arr, " "); # 分离日期和IP
day_ip[arr[1]][arr[2]] = count[key]; # 按日期和IP累计
}
for (day in day_ip) {
max_ip = "";
max_count = 0;
for (ip in day_ip[day]) { # 找到每天访问次数最多的 IP
if (day_ip[day][ip] > max_count) {
max_ip = ip;
max_count = day_ip[day][ip];
}
}
printf "Date: %s, IP: %s, Visits: %d\n", day, max_ip, max_count;
}
}'