本文节选自《Netkiller Linux 手札》
下面是一个脚本你可以放在crontab中运行,每个一定时间运行一次。
#!/bin/bash
########################################
# Homepage: http://netkiller.github.io
# Author: neo <netkiller@msn.com>
########################################
PIPE=/var/tmp/pipe
pidfile=/var/tmp/$0.pid
BLACKLIST=/var/tmp/black.smtpd.lst
WHITELIST=/var/tmp/white.smtpd.lst
LOGFILE=/var/log/maillog
DAY=5
########################################
if [ -z "$( egrep "CentOS|7." /etc/centos-release)" ]; then
echo 'Only for CentOS 7.x'
exit
fi
if [ -f $BLACKLIST ]; then
find $BLACKLIST -type f -mtime +${DAY} -delete
fi
if [ ! -f ${BLACKLIST} ]; then
touch ${BLACKLIST}
fi
if [ ! -f ${WHITELIST} ]; then
touch ${WHITELIST}
fi
for ipaddr in $(grep "too many errors after AUTH from" ${LOGFILE} | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | sort | uniq -c | sort -r -n | head -n 20| awk '{print $2}')
do
if [ $(grep -c $ipaddr ${WHITELIST}) -gt 0 ]; then
continue
fi
if [ $(grep -c $ipaddr ${BLACKLIST}) -eq 0 ] ; then
echo $ipaddr >> ${BLACKLIST}
iptables -I INPUT -p tcp --dport 25 -s $ipaddr -j DROP
#iptables -I INPUT -s $ipaddr -j DROP
fi
done