根据ssh远程登录错误次数自动限制IP 防止ssh暴力攻击
我们可以在第三种办法基础上,通过shell脚本自动将错误登陆10次以上的IP加入拒绝列表,首先编写脚本如下:
vim secure_ssh.sh
#! /bin/bash
cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}' > /home/sxdgy/lastb
for i in `cat /home/sxdgy/lastb`
do
IP=`echo $i |awk -F= '{print $1}'`
NUM=`echo $i|awk -F= '{print $2}'`
if [ ${#NUM} -gt 1 ]; then
grep $IP /etc/hosts.deny > /dev/null
if [ $? -gt 0 ];then
echo "sshd:$IP:deny" >> /etc/hosts.deny
fi
fi
done
然后给脚本附上执行权限,再加入到自动任务中,根据自身情况设置好执行间隔:
chmod u+x secure_ssh.sh
vim /etc/crontab
#在末尾加上自动任务,一小时执行一次
01 * * * * root /root/secure_ssh.sh
保存退出,等到触发时间到了就可以看到已经在/etc/hosts.deny文件中加入许多拒绝的IP:
启动定时任务
systemctl start crond
重启 SSHD服务
systemctl restart sshd