Loading

centos7禁止 SSH 登录失败超过30次的IP

使用 firewalld 禁止 SSH 登录失败超过30次的IP

概述

在CentOS 7中,一般默认安装了firewalld
动态添加失败登录超过30次的IP地址到防火墙规则中,禁止这些IP的访问。
编写和使用脚本,通过 firewalld 来实现;
注意iptables不适用,但大差不差。

步骤

1. 安装 firewalld

确保 firewalld 已经安装并运行:

sudo yum install firewalld
sudo systemctl enable firewalld
sudo systemctl start firewalld

2. 创建脚本 ban_failed_ssh_firewalld.sh

在合适的位置创建一个新的脚本文件 ban_failed_ssh_firewalld.sh

sudo vi /root/ban_failed_ssh_firewalld.sh

将以下内容复制到脚本文件中:

#!/bin/bash

LOG_FILE="/var/log/secure"

# 检查日志文件是否存在
if [ ! -f "$LOG_FILE" ]; then
    echo "日志文件 $LOG_FILE 不存在!"
    exit 1
fi

# 检查是否有读取日志文件的权限
if [ ! -r "$LOG_FILE" ]; then
    echo "没有读取日志文件 $LOG_FILE 的权限,请以root用户运行此脚本!"
    exit 1
fi

# 设置失败登录次数阈值
THRESHOLD=30

# 提取失败登录的IP并统计
echo "提取失败登录超过 $THRESHOLD 次的IP地址..."
FAILED_IPS=$(grep "Failed password" $LOG_FILE | awk '{print $(NF-3)}' | sort | uniq -c | sort -nr | awk -v threshold=$THRESHOLD '$1 > threshold {print $2}')

# 调试输出,检查提取的IP地址
echo "提取的IP地址:"
echo "$FAILED_IPS"

# 检查是否有符合条件的IP
if [ -z "$FAILED_IPS" ]; then
    echo "没有IP地址登录失败超过 $THRESHOLD 次。"
    exit 0
fi

# 禁止这些IP通过firewalld
echo "添加以下IP到firewalld黑名单:"
for IP in $FAILED_IPS; do
    echo $IP
    firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='$IP' reject"
done

# 重新加载firewalld服务以应用更改
echo "重新加载firewalld服务..."
firewall-cmd --reload

echo "操作完成。"

3. 赋予脚本执行权限

赋予脚本执行权限:

chmod +x /root/ban_failed_ssh_firewalld.sh

4. 运行脚本

root 用户运行脚本:

sudo /root/ban_failed_ssh_firewalld.sh

自动化

执行此脚本,可选用 cron 定时任务。

1. 编辑 crontab 文件

编辑 crontab 文件:

crontab -e

2. 添加定时任务

例如,每小时运行一次脚本:

0 * * * * /root/ban_failed_ssh_firewalld.sh

/root/ban_failed_ssh_firewalld.sh 替换为your脚本路径。

调试步骤

出现问题可以尝试以下做法:

1. 手动检查日志文件

运行以下命令,确保日志文件存在并且可以读取:

ls -l /var/log/secure
cat /var/log/secure | head

2. 检查提取的IP地址

运行以下命令,手动提取失败的登录IP地址,并检查输出是否正确:

grep "Failed password" /var/log/secure | awk '{print $(NF-3)}' | sort | uniq -c | sort -nr | awk '$1 > 30 {print $2}'

总结

使用 firewalld 自动阻止SSH登录失败超过30次的IP,免受暴力破解困扰。

posted @ 2024-06-24 09:44  夷某蓁  阅读(246)  评论(0)    收藏  举报