#!/bin/bash
j=0
var=3
interface_name="/getmobilevalidcode.do"
while true ;do
dtime=`date '+%F +%T'`
dy=`date '+%F'`
unix_day=`date '+%s'`
tmp_ip_view_file=/tmp/tmp_ip.txt_view
tmp_ip_store_ip_drop=/tmp/.store_ip.txt
if [[ ! -f ${tmp_ip_view_file} ]] ;then
touch ${tmp_ip_view_file}
fi
if [[ ! -f ${tmp_ip_store_ip_drop} ]] ;then
touch ${tmp_ip_store_ip_drop}
fi
if [[ $j -gt 360 ]];then
echo "j=$j now doing iptables -F"
echo "${dtime} j=$j now doing iptables -F,free all ip continue" >>/home/richmail/logs/ip_drop.log.${dy}
iptables -F
j=0
continue;
else
echo "j = $j -lt 360"
fi
echo "################################################################monitor begin"
echo -e "\033[31;49mACCESS LOG getmobilevalidcode:\033[0m"
tail -100 /home/richmail/logs/mail.nginx_ssl.log |grep "$interface_name" |awk -v "ut=${unix_day}" '{a[$1]++}END{for(i in a ){printf "%-3d %-15d %s\n", a[i],ut,i}}' |sort -nr >${tmp_ip_view_file}
iptables -vnL |grep -P "^\s+\d"|awk '{print $8}'|grep -P "\d+\.\d+\.\d+\.\d+">/tmp/.st_iptables
cat /tmp/tmp_ip.txt_view|while read num ut ip ;do
if [[ $num -gt $var ]]; then
#echo " full ${tmp_ip_store_ip_drop}"
if [[ -z $(grep "$ip" /tmp/.st_iptables|grep -v "grep") ]];then
echo "***************$ut $ut_file $ip"
echo "iptables -I INPUT -s $ip -p tcp -m tcp --dport 443 -j DROP"
echo "iptables -I INPUT -s $ip -p tcp -m tcp --dport 80 -j DROP"
echo "${dtime} j=$j now doing iptables drop $ip num=$num threshold=$var interval=5" >>/home/richmail/logs/ip_drop.log.${dy}
iptables -I INPUT -s $ip -p tcp -m tcp --dport 443 -j DROP
iptables -I INPUT -s $ip -p tcp -m tcp --dport 80 -j DROP
else
echo "${dtime} j=$j it is not need to drop as it is in iptables ip=$ip num=$num threshold=$var interval=5" >>/home/richmail/logs/ip_drop.log.${dy}
fi
fi
done
((j++))
sleep 5;
done