nginx访问日志,写一个统计一个时间段内,每一分钟有多少个IP访问的shell脚本怎么写?
可以使用 Shell 脚本结合 awk 命令和 sed 命令来实现对 Nginx 访问日志的统计。具体实现如下:
#!/bin/bash
# 访问日志文件路径
access_log="/var/log/nginx/access.log"
# 时间段
start_time=$(date -d "yesterday 00:00:00" "+%d/%b/%Y:%H:%M:%S")
end_time=$(date "+%d/%b/%Y:%H:%M:%S")
# 统计每分钟的 IP 访问数
awk -v start="$start_time" -v end="$end_time" \
'$4 > "[" start && $4 < "[" end \
{split($4,a,":"); time=a[2]":"a[3]; ip[$1,time]++} \
END {for (i in ip) {split(i, a, SUBSEP); ips[a[1]][a[2]]++} \
for (ip in ips) {printf("%s,", ip); \
for (time=0; time<=59; time++) \
{minute=sprintf("%02d", time); \
printf("%d,", ips[ip][minute])} \
printf("\n")}}' $access_log | \
sed 's/^[ \t]*//;s/[ \t]*$//' > ip_stats.txt
该脚本将访问时间段内每分钟的 IP 访问次数统计到了一个名为 ip_stats.txt 的文本文件中,格式如下:
IP地址,00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59
192.168.1.1,0,2,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5
192.168.1.2,1,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5
其中,第一列代表 IP 地址,后面的列代表每分钟的IP访问次数。