主题
Fail2ban:失败登录锁定 SSH IP
Fail2ban 通过扫描认证日志,在短时间内多次失败登录时自动封禁来源 IP,常用于防护 SSH 暴力破解。
NOTE
下文示例中 SSH 端口为 35738,请改成你实际使用的端口;默认 22 可写成 ssh 或 22。
一、安装 Fail2ban
1.1 CentOS / Rocky / AlmaLinux
Fail2ban 一般在 EPEL 源中:
bash
yum install -y epel-release
yum install -y fail2ban fail2ban-systemd较新系统可用 dnf:
bash
dnf install -y epel-release
dnf install -y fail2ban fail2ban-systemd1.2 OpenEuler
bash
dnf install -y fail2ban若仓库中无该包,可先启用对应扩展源后再安装,或从发行版文档推荐的源安装。
1.3 Ubuntu / Debian
bash
apt update
apt install -y fail2ban安装完成后确认版本:
bash
fail2ban-client -V二、写入 jail.local 配置
WARNING
不要直接改 jail.conf(升级会被覆盖)。自定义配置写在 /etc/fail2ban/jail.local。
bash
cat > /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
backend = systemd
[sshd]
enabled = true
filter = sshd[mode=aggressive]
logpath = %(sshd_log)s
port = 35738
maxretry = 4
findtime = 300
bantime = 600
banaction = iptables-multiport
action = %(action_)s[name=%(__name__)s, blocktype=REJECT]
[recidive]
enabled = true
backend = polling
logpath = /var/log/fail2ban.log
maxretry = 3
findtime = 86400
bantime = 604800
banaction = iptables-allports
action = %(action_)s[name=%(__name__)s, protocol=all, blocktype=DROP]
EOF配置说明:
| 项 | 含义(本示例) |
|---|---|
sshd.maxretry | 5 分钟内失败 4 次即封禁 |
sshd.findtime | 统计窗口 300 秒 |
sshd.bantime | 单次封禁 600 秒 |
recidive | 反复被封的 IP 升级为更长封禁(约 7 天) |
blocktype=REJECT | SSH jail 使用 REJECT |
blocktype=DROP | recidive 直接 DROP |
三、启动并设置开机自启
bash
systemctl restart fail2ban
systemctl enable fail2ban
systemctl status fail2ban四、状态查看
bash
fail2ban-client status
fail2ban-client status sshd
fail2ban-client status recidive查看 ban 动作类型:
bash
# sshd 失败返回拒绝动作(REJECT)
fail2ban-client get sshd action iptables-multiport blocktype
# recidive 直接丢包(DROP)
fail2ban-client get recidive action iptables-allports blocktype预期输出示例:
bash
REJECT --reject-with icmp-port-unreachable
DROP五、常用运维命令
解封某个 IP:
bash
fail2ban-client set sshd unbanip 1.2.3.4查看当前被封 IP:
bash
fail2ban-client status sshd