部署在公网的服务器,一直遭受攻击
查看登录日志tail -f /var/log/secure
可以看到一直有ip在恶意攻击
简单写个脚本,统计失败登录的ip加入黑名单
1 查找出错误登录的日志
cat /var/log/secure | awk '/^.*(F|f)ailed.*/'|head -n 10
2 从结果中过滤出ip
cat /var/log/secure | awk '/^.*(F|f)ailed.*/'|egrep "from ([0-9]+.){3}[0-9]+" -o
3 替换为符合/etc/hosts.deny格式
tac /var/log/secure | awk '/^.*(F|f)ailed.*/'|egrep "from ([0-9]+.){3}[0-9]+" -o|sed 's#from #sshd:#g'
这里只禁用sshd服务
4 统计登录失败ip数量,并按失败次数归类
tac /var/log/secure | awk '/^.*(F|f)ailed.*/'|egrep "from ([0-9]+.){3}[0-9]+" -o|sed 's#from #sshd:#g' |sort | uniq -c | sort -nr
5 最终脚本
#!/bin/sh
tac /var/log/secure | awk '/^.*(F|f)ailed.*/'|egrep "from ([0-9]+.){3}[0-9]+" -o|sed 's#from #sshd:#g' |sort | uniq -c | sort -nr > /data/tempip
#登录失败次数超过10次的ip
ip=`cat /data/tempip | awk '{if($1>10)print $2}'`
for line in $ip
do
result=$(grep $line /etc/hosts.deny)
#判断ip是否已经被屏蔽
if [ -z "$result" ]; then
#未屏蔽的ip进行屏蔽
echo "$line" >> /etc/hosts.deny
fi
done
6 添加定时任务
*/1 * * * * /bin/bash /data/blackip.sh
7 最终效果
查看登录日志