#!/bin/bash source /etc/profile HOST_IP="172.16.1.122" DROP_IP_FILE="/tmp/drop_ip.log" [ ! -f $DROP_IP_FILE ] touch $DROP_IP_FILE DATE="$(date +%d/%b/%Y:%H:%M)" # nginx的时间格式为"01/Sep/2020:10:51:51" # 当前DATE的时间格式为"
#!/bin/bash
source /etc/profile
HOST_IP="172.16.1.122"
DROP_IP_FILE="/tmp/drop_ip.log"
[ ! -f $DROP_IP_FILE ] && touch $DROP_IP_FILE
DATE="$(date +%d/%b/%Y:%H:%M)"
# nginx的时间格式为"01/Sep/2020:10:51:51"
# 当前DATE的时间格式为"01/Sep/2020:10:51"
# 目的是取nginx一分钟的访问日志
LOG_FILE="/usr/local/nginx/logs/access.log"
ABNORMAL_IP="$(tail -n5000 $LOG_FILE |grep $DATE |awk '{a[$1]++} END {for(i in a) if(a[i]>10) print i}')"
for IP in $ABNORMAL_IP; do
if [ $(firewall-cmd --list-rich-rules |grep -c "$IP") -eq 0 ]; then
firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='$IP' reject" &>/dev/null
firewall-cmd --reload &>/dev/null
echo "$(date +'%F_%T') $IP" >> $DROP_IP_FILE
fi
done
if [ $ABNORMAL_IP ]; then
echo "Server $HOST_IP AT $DATE Block ip address $ABNORMAL_IP" |mail -s "Server $HOST_IP Block ip address" 2504164765@qq.com
fi
# iptables 方式过滤
# if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
# iptables -I INPUT -s $IP -j DROP
# fi