脚本
#!/bin/bash
DEFINE="10"
ips=`lastb | awk '{print $3}' | egrep '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'`
for ip in $ips
do
NUM=`lastb | grep $ip | wc -l`
if [ $NUM -gt $DEFINE ];then
grep $ip /etc/hosts.deny > /dev/null
if [ $? -gt 0 ];then
echo "sshd:$IP:deny" >> /etc/hosts.deny
echo $ip"加入黑名单成功"
fi
fi
done
脚本解析
首先根据lastb
命令列出登录失败列表,如下:
[user@hecs script]# lastb
root ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
root ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
root ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
test ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
test ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
test ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
test ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
postgres ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
postgres ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
postgres ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
postgres ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
oracle ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
oracle ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
oracle ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
oracle ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
mysql ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
oracle ssh:notty 119.8.55.100 Tue Nov 2 00:01 - 00:01 (00:00)
oracle ssh:notty 119.8.55.100 Tue Nov 2 00:00 - 00:00 (00:00)
mysql ssh:notty 119.8.55.100 Tue Nov 2 00:00 - 00:00 (00:00)
ghost ssh:notty 119.8.55.100 Tue Nov 2 00:00 - 00:00 (00:00)
odoo ssh:notty 119.8.55.100 Tue Nov 2 00:00 - 00:00 (00:00)
...
我们使用awk
命令获取输出结果的第三列内容:
[user@hecs script]# lastb | awk '{print $3}'
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
Mon
因为当中有些信息并不是登陆失败,比如最后一行,所以我们再用正则表达式筛选出所有的ip:
[user@hecs script]# lastb | awk '{print $3}' | egrep '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
119.8.55.100
这时候就都是IP了,然后我们再通过遍历IP列表,通过wc -l
命令得到IP攻击的次数,如果大于我们设置的阈值则加入到/etc/hosts.deny
文件中进行封禁
for ip in $ips
do
NUM=`lastb | grep $ip | wc -l`
if [ $NUM -gt $DEFINE ];then
grep $ip /etc/hosts.deny > /dev/null
if [ $? -gt 0 ];then
echo "sshd:$IP:deny" >> /etc/hosts.deny
echo $ip"加入黑名单成功"
fi
fi
done
下面是我们自己运营的微信小程序“但行趣事”和公众号“但行趣事”,更多的技术文章以及视频我会放到小程序和公众号当中,有志同道合的小伙伴也可以在小程序(联系客服按钮)或者公众号(直接留言)当中联系我们
|
|