#!/usr/bin/bash

#Tate:2022.3.30
#Author:Yingjian
#function: 统计5分钟之内的访问ip
#env

#脚本存放的目录
workdir=`cd $(dirname $0);pwd`

#if [ $# -eq 0 ];then
#echo "Usage: $0 {统计几分钟内的ip}"
#exit 2
#fi
#nginx日志文件路径
logfile=/var/log/nginx/access.log
#设置5分钟
last_minutes=300

start_time=`date -d "$last_minutes minutes ago" +"%H:%M:%S"`
#echo $start_time

stop_time=`date +"%H:%M:%S"`
#echo $stop_time

tail -n 10000 $logfile |awk -v st="$start_time" -v et="$stop_time" '{t=substr($4,RSTAR+14,21);if(t>=st && t<=et) {print $0}}' \
|awk '{print $1}'|sort |uniq -c|sort -nr > $workdir/5min_log_ip.txt

#统计大于阈值的ip
ip=`cat $workdir/5min_log_ip.txt |awk '{if($1 >=2)print $2}'`

for line in $ip
do
echo "$line" >>$workdir/5min_deny_ip.txt
done
