fail2ban 基本用法

给我讲讲这个 fail2ban 基本用法

fail2ban 是一个用于保护 Linux 服务器的安全工具,它可以检测系统日志中的可疑活动(如 SSH 爆破攻击)并自动封禁恶意 IP 地址。

1. 安装

在 Ubuntu/Debian 上:

sudo apt update && sudo apt install fail2ban -y

在 CentOS/RHEL 上:

sudo yum install epel-release -y
sudo yum install fail2ban -y

2. 配置

Fail2ban 的默认配置文件位于 /etc/fail2ban/jail.conf,但不建议直接修改它,而是创建 jail.local

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

然后编辑 jail.local 进行配置:

sudo nano /etc/fail2ban/jail.local

常见配置项:

[DEFAULT]
bantime  = 3600   # 封禁时间(秒)
findtime = 600    # 在这个时间窗口内多次失败则触发封禁
maxretry = 5      # 允许的最大失败尝试次数

3. 启用 SSH 保护

jail.local 中找到 [sshd] 规则并启用:

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log  # Ubuntu/Debian
# logpath = /var/log/secure  # CentOS
maxretry = 3

4. 启动 Fail2Ban

sudo systemctl enable --now fail2ban
sudo systemctl status fail2ban

5. 查看被封禁的 IP

sudo fail2ban-client status sshd

6. 手动封禁/解封 IP

封禁 IP:

sudo fail2ban-client set sshd banip 192.168.1.100

解封 IP:

sudo fail2ban-client set sshd unbanip 192.168.1.100

这样,你的服务器就能自动防御暴力破解攻击了! 🚀