自动屏蔽登录失败3次以上的用户再登录系统

前言

暴露在公网上Linux经常会有人暴力破解linux上的用户,通过以下脚本实现屏蔽通过密码登录linux失败超过三次的ip地址再次登录系统

脚本源码

/root/secure.sh

#!/bin/bash

# 定义变量
LOG_FILE="/var/log/secure"
INTERVAL=600 # 检测间隔,单位为秒
THRESHOLD=3  # 登录失败次数阈值

# 定义函数用于屏蔽 IP 地址
block_ip() {
    ip=$1
    echo "Blocking IP address: $ip"
    iptables -A INPUT -s $ip -j DROP
    echo "已屏蔽 IP 地址 $ip"
}

# 定义函数用于提取登录失败次数超过阈值的用户并屏蔽其 IP 地址
block_failed_users() {
    failed_users=$(grep "Failed password" $LOG_FILE | awk '{print $9}' | sort | uniq -c | awk '{if ($1 >= '$THRESHOLD') print $2}')
    for user in $failed_users; do
        ip=$(grep "Failed password for $user" $LOG_FILE | tail -n $THRESHOLD | awk '{print $(NF-3)}' | head -n 1)
        block_ip $ip
    done
}

# 定义函数用于删除重复的iptables规则
remove_duplicate_rules() {
    iptables-save > /tmp/iptables.bak
	iptables -F
	awk '!seen[$0]++' /tmp/iptables.bak > /tmp/iptables.bak.tmp && mv -f /tmp/iptables.bak.tmp /tmp/iptables.bak
	iptables-restore < /tmp/iptables.bak
}

# 持续运行脚本
while true; do
    block_failed_users
    remove_duplicate_rules
    sleep $INTERVAL
done

uniq -c 是一个 Linux 命令,用于在文本文件中查找重复的行,并计算它们的数

通过systemd调用

[Unit]
Description=Secure Log Monitor Service
After=network.target

[Service]
Type=simple
ExecStart=/bin/bash /root/secure.sh
Restart=always

[Install]
WantedBy=multi-user.target

启用并启动该服务

sudo systemctl daemon-reload
sudo systemctl enable secure.service
sudo systemctl start secure.service

现在,secure.sh 脚本将会作为一个 systemd 服务在系统启动时自动运行,并且会在运行期间持续监控 /var/log/secure 日志文件,执行相应的操作。

验证

[root@docker ~]# systemctl status secure
● secure.service - Secure Log Monitor Service
   Loaded: loaded (/etc/systemd/system/secure.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2024-04-01 17:21:13 CST; 3min 2s ago
 Main PID: 16678 (bash)
   CGroup: /system.slice/secure.service
           ├─16678 /bin/bash /root/secure.sh
           └─16943 sleep 60

Apr 01 17:22:13 huawei bash[16678]: Blocking IP address: 58.180.17.54
Apr 01 17:22:13 huawei bash[16678]: 已屏蔽 IP 地址 58.180.17.54
Apr 01 17:23:13 huawei bash[16678]: Blocking IP address: 36.111.189.80
Apr 01 17:23:13 huawei bash[16678]: 已屏蔽 IP 地址 36.111.189.80
Apr 01 17:23:13 huawei bash[16678]: Blocking IP address: 58.180.17.54
Apr 01 17:23:13 huawei bash[16678]: 已屏蔽 IP 地址 58.180.17.54
Apr 01 17:24:13 huawei bash[16678]: Blocking IP address: 36.111.189.80
Apr 01 17:24:13 huawei bash[16678]: 已屏蔽 IP 地址 36.111.189.80
Apr 01 17:24:13 huawei bash[16678]: Blocking IP address: 58.180.17.54
Apr 01 17:24:13 huawei bash[16678]: 已屏蔽 IP 地址 58.180.17.54
[root@docker ~]# 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值