以下为节选网上教程:
最近不知为啥,很多国外IP开始SSH暴力攻击服务器,改了ssh端口也没用,继续被暴力破解,应该是有脚本在批量破解就在想怎么防护,运维同事曾大神推荐了个faild2ban,使用起来感觉麻烦,于是网上搜索了个脚本改改,效果居然还挺好的。
脚本内容如下:
文件名secure_ssh.sh ,我存放在/opt目录下面(centos系统)
#! /bin/bash
cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}' > /usr/local/bin/black.txt
for i in `cat /usr/local/bin/black.txt`
do
IP=`echo $i |awk -F= '{print $1}'`
NUM=`echo $i|awk -F= '{print $2}'`
if [ $NUM -gt 5 ];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 文件,捞取密码失败五次以上IP信息 ,然后写入到/etc/hosts.deny,禁止相关ip ssh访问服务器,加入服务器没有secure 文件,则可以使用lastb 命令(用于查看失败登录ip信息)
效果如下
[root@VM-16-10-centos opt]# lastb -n 10
ssh:notty 82.157.47.238 Thu Aug 25 00:28 - 00:28 (00:00)
ssh:notty 64.62.197.137 Wed Aug 24 21:07 - 21:07 (00:00)
pi ssh:notty 99.199.192.24 Wed Aug 24 18:52 - 18:52 (00:00)
pi ssh:notty 99.199.192.24 Wed Aug 24 18:52 - 18:52 (00:00)
pi ssh:notty 99.199.192.24 Wed Aug 24 18:52 - 18:52 (00:00)
pi ssh:notty 99.199.192.24 Wed Aug 24 18:52 - 18:52 (00:00)
read ssh:notty 92.255.85.70 Wed Aug 24 16:26 - 16:26 (00:00)
read ssh:notty 92.255.85.70 Wed Aug 24 16:26 - 16:26 (00:00)
pi ssh:notty 110.19.208.233 Wed Aug 24 14:43 - 14:43 (00:00)
pi ssh:notty 110.19.208.233 Wed Aug 24 14:43 - 14:43 (00:00)
awk 命令 检索 信息
sort|uniq -c 排序。并汇总出现次数,并将找到的ip输出到black.txt 并遍历black文件再和/etc/hosts.deny文件比较
处理完脚本,再给加到定时任务里面
先查看下定时任务
crontab -l
然后编辑
crontab -e
在出现的定时任务编辑加上下面语句,每隔15分钟(linux定时任务表达式从分钟起)执行一下脚本,汇总下攻击IP,并加入黑名单
*/15 * * * * sh /opt/secure_ssh.sh
然后按 esc 输入:wq!命令保存
如果担心自己密码输入错误次数多,就把自己的 ip 加入的 hosts.allow里面
查看黑名单列表是否记录
cat /usr/local/bin/black.txt
查看黑名单列表看是否添加进去了
cat /etc/hosts.deny