云主机开启sshd一般都会遭到各种IP的暴力破解
自己编写脚本即可实现sshd黑名单的功能
#!/bin/bash
cat /var/log/secure | awk '/Failed/{print $(NF-3)}' | sort | uniq -c | awk '{print $2"="$1;}' > /root/black.txt
DEFINE="10"
for i in `cat /root/black.txt`
do
IP=`echo | awk '{split("'${i}'", array, "=");print array[1]}'`
NUM=`echo | awk '{split("'${i}'", array, "=");print array[2]}'`
if [ $NUM -gt $DEFINE ];then
grep $IP /etc/hosts.deny > /dev/null
if [ $? -gt 0 ];then
echo "sshd:$IP:deny" >> /etc/hosts.deny
fi
fi
done
脚本原理
- 读取
/var/log/secure
里面的sshd失败记录, 通过awk将其转存成IP=次数
的文本格式 - 从文本中读取失败次数大于指定数值的IP, 如果不在sshd黑名单则加入
定期执行
crontab -e
加入如下计划任务即可
1 */3 * * * /usr/bin/bash /usr/src/jb/sshd_autoban.sh >/dev/null 2>&1