【www.bbyears.com--CentOS】
脚本
#! /bin/bash
cat /var/log/secure|awk "/Failed/{print $(NF-3)}"|sort|uniq -c|awk "{print $2"="$1;}" > /root/black.txt #筛选出状态为Failed的ip和次数
cat /var/log/secure|awk "/Invalid user/{print $NF}"|sort|uniq -c|awk "{print $2"="$1;}" >> /root/black.txt #筛选出状态为Invalid user的ip和次数
DEFINE="20" #规定允许次数为20次
for i in `cat /root/black.txt`
do
IP=`echo $i |awk -F= "{print $1}"`
NUM=`echo $i|awk -F= "{print $2}"`
if [ $NUM -gt $DEFINE ];
then
grep $IP /etc/hosts.deny > /dev/null
if [ $? -gt 0 ];
then
echo "sshd:$IP" >> /etc/hosts.deny
fi
fi
done
规定当登录失败或者非法用户的ip次数达到20次后就把ip加入到hosts.deny中。
因为secure日志文件是每周六就会自动存档,于是我们可以写个排程定制去跑这个脚本
每天凌晨1点运行
0 1 * * * /usr/local/bin/ssh_black.sh 2>&1 >>/dev/null