Centos-监控IP频繁尝试登录服务器封禁脚本
前言
因为虚拟机之前已部署fail2ban
,但是存在漏封禁的情况,查看日志发现一些漏扫啥的会几分钟登录一次或者就十几分钟才尝试1-2次导致漏封情况。
那就继续每天定时再执行一次脚本再去把漏封的封禁掉
脚本
该脚本的作用是监控IP登录失败次数,如果某个IP的登录失败次数超过设定的最大次数,则阻止该IP的进一步登录尝试。
通过iptables
防火墙阻止连接,当一个IP尝试登录次数超过登录失败次数,iptables
会阻止来自该IP的所有连接。
#!/bin/bash
function check(){
# 设置最大失败次数
MAX_FREQUENCY=10
# 获取所有登录失败的IP并统计次数
IP_COUNT=$(lastb | awk '{print $3}' | egrep "[1-9]+" | sort | uniq -c | awk '$1 >= 'MAX_FREQUENCY' {print $2}')
# 遍历所有登录失败次数超过阈值的IP并将其阻止
for IP in ${IP_COUNT}
do
# 检查IP是否已经在iptables策略中
if iptables -xvnL | grep $IP 1>/dev/null; then
echo "$IP is already exist iptables."
else
echo "`date +"%F %H:%M:%S"` Blocking $IP ..."
iptables -A INPUT -s $IP -j DROP
fi
done
}
check
# 执行完后清空之前登录记录。
date_time=`date +"%Y%m%d%H%M%S"`
mv /var/log/btmp /var/log/btmp.$date_time
echo > /var/log/btmp
再使用crontab 每日/每几天定时执行一次即可。
执行效果:
[root@iZwz9bryvndk026nx3zcxxZ ~]# sh checkLoginNum.sh
2024-01-15 09:35:42 Blocking 106.14.158.16 ...
2024-01-15 09:35:42 Blocking 139.19.117.195 ...
2024-01-15 09:35:42 Blocking 139.196.228.183 ...
2024-01-15 09:35:42 Blocking 139.224.51.180 ...
2024-01-15 09:35:42 Blocking 146.190.136.234 ...
2024-01-15 09:35:42 Blocking 149.129.174.11 ...
2024-01-15 09:35:42 Blocking 157.148.120.98 ...
2024-01-15 09:35:42 Blocking 159.203.167.74 ...
2024-01-15 09:35:42 Blocking 159.75.90.220 ...
2024-01-15 09:35:42 Blocking 183.136.225.31 ...
2024-01-15 09:35:42 Blocking 42.194.196.180 ...
2024-01-15 09:35:42 Blocking 47.102.124.115 ...
2024-01-15 09:35:42 Blocking 47.102.148.183 ...
2024-01-15 09:35:42 Blocking 47.243.170.145 ...
2024-01-15 09:35:42 Blocking 47.74.44.221 ...
2024-01-15 09:35:42 Blocking 8.134.191.171 ...
2024-01-15 09:35:42 Blocking 89.58.5.194 ...
[root@iZwz9bryvndk026nx3zcxxZ ~]# sh checkLoginNum.sh
106.14.158.16 is already blocked.
139.19.117.195 is already blocked.
139.196.228.183 is already blocked.
139.224.51.180 is already blocked.
146.190.136.234 is already blocked.
149.129.174.11 is already blocked.
157.148.120.98 is already blocked.
159.203.167.74 is already blocked.
159.75.90.220 is already blocked.
183.136.225.31 is already blocked.
42.194.196.180 is already blocked.
47.102.124.115 is already blocked.
47.102.148.183 is already blocked.
47.243.170.145 is already blocked.
47.74.44.221 is already blocked.
8.134.191.171 is already blocked.
89.58.5.194 is already blocked.