参考文章:https://blog.csdn.net/weixin_52270081/article/details/121496140

最近服务器一直不停的有人跑字典,为了节约资源,保证服务器安全。故参考网上文章编写了shell脚本,以下为实现方法。

查看登录记录

sudo lastb  #查看登录失败记录
sudo last  #查看登录成功记录

日志文件介绍

1./var/run/utmp:记录当前正在登录系统的用户信息,默认由who和w记录当前登录用户的信息,uptime记录系统启动时间
2./var/log/wtmp:记录当前正在登录和历史登录系统的用户信息,默认由last命令查看
3./var/log/btmp:记录失败的登录尝试信息,默认由lastb命令查看
本脚本使用btmp日志。

编写脚本

Ubuntu的IP黑名单位置为/etc/hosts.deny,格式为ALL:IP,故内容如下:

#!/bin/bash
#将失败次数达到5次的IP加入黑名单
list=$(sudo lastb | awk '{print $3}' | sort | uniq  -c | awk '{if ($1 > 5) print $2}')
for ip in ${list}
do
        echo ALL: ${ip} >> /etc/hosts.deny  #加入黑名单
        echo > /var/log/btmp  #清空失败记录,防止重复添加
done

将脚本加入定时任务,每两小时执行一次

使用root添加定时任务:

sudo crontab -e

加入:

0 */2 * * * /bin/bash xxx.sh位置

附上crontab定时计算工具:https://tool.lu/crontab