LOGPATH="/home/wwwlogs/"
LOGFILE="y.log"
LAST_MINUTES=35
MAX_REQUEST=200
FIREWALL_SERVICE="firewall"
CMD=$1
if [ "${CMD}" = "" ]; then
CMD="run"
else
CMD=$1
fi
function filterIP()
{
logfile=$1
echo '' > log_ip_ranking
tac $logfile | grep "${day}" | awk '{print $1,$4;}' | tr '[' ' ' | tr ':' ' ' | tr '/' ' ' \
| awk -v st="$start_time" -v et="$stop_time" '{ t=$2$5$6;if (t>=st && t<=et ) {print $1;}}' | sort | uniq -c | sort -nr > $LOGPATH/log_ip_ranking
ip_top=`cat $LOGPATH/log_ip_ranking | head -1 | awk '{print $1}'`
ips=`cat $LOGPATH/log_ip_ranking | awk -v max_num="${MAX_REQUEST}" '{if($1>=max_num) print $2}'`
Log "====== ${logfile} ======"
msg=""
for ip in $ips
do
ret=`cat ${LOGPATH}blacklog | grep ${ip}`
if [ -z "$ret" ];then
cmd=`echo ${ADD_BLACKLIST_CMD}| sed "s/{{ip}}/${ip}/g"`
read num ipstr < <(cat $LOGPATH/log_ip_ranking | grep ${ip})
tmp="IP:${ipstr} 访问次数:${num}"
msg="${msg}\n ${tmp}"
$cmd
echo $tmp
echo $ip >> ${LOGPATH}blacklog
else
Log "${ip},已存在处理历史记录中,跳过..."
fi
done
$RELOAD_SERVICE_CMD > /dev/null 2>&1
if [ -n "$msg" ];then
sendMsg "以下IP访问【${LAST_MINUTES}】分钟内访问超过【${MAX_REQUEST}】次已拉黑\n文件:${logfile}\n时间范围:${start_time} - ${stop_time}\n${msg}"
Log ''
fi
Log "====== END ======"
}
function Log()
{
echo $@
}
function run()
{
day=`date +"%d/%b/%Y"`
start_time=`date -d"${LAST_MINUTES} minutes ago" +"%d%H%M"`
stop_time=`date +"%d%H%M"`
file_list=`ls ${LOGPATH}${LOGFILE}`
case "${FIREWALL_SERVICE}" in
firewall)
ADD_BLACKLIST_CMD='firewall-cmd --permanent --ipset=blacklist --add-entry={{ip}}'
RELOAD_SERVICE_CMD='firewall-cmd --reload'
;;
iptables)
ADD_BLACKLIST_CMD='ipset add blacklist {{ip}}'
RELOAD_SERVICE_CMD=''
;;
esac
for file in $file_list
do
filterIP $file
done
}
function sendMsg()
{
msg_content=`echo -e $@`
}
function initIpTables()
{
yum -y install ipset
ipset create blacklist hash:ip
iptables -I INPUT -m set --match-set blacklist src -p tcp --destination-port 80:8080 -j DROP
Log "IPTables init success."
}
function initFirewall()
{
firewall-cmd --permanent --new-ipset=blacklist --type=hash:ip
firewall-cmd --permanent --add-rich-rule 'rule family="ipv4" source ipset="blacklist" port port="80-8080" protocol="tcp" drop'
firewall-cmd --reload
Log "Firewall init success."
}
function status()
{
echo "###### Service: ${FIREWALL_SERVICE} ######"
case "${FIREWALL_SERVICE}" in
firewall)
firewall-cmd --permanent --info-ipset=blacklist
;;
iptables)
ipset list
;;
esac
}
function init()
{
case "${FIREWALL_SERVICE}" in
firewall)
initFirewall
;;
iptables)
initIpTables
;;
esac
}
function main()
{
case "${CMD}" in
init)
init
;;
run)
run
;;
status)
status
;;
*)
echo "Usage: $0 {init|run|status}"
;;
esac
}
main