mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
338 字
1 分钟
fail2ban
2026-01-17
统计加载中...

检查 SSH 端口是否被爆破#

journalctl -u ssh

如果在日志中看到了大量的不明 IP 地址在进行尝试,就说明有人在尝试爆破了。

安装 Fail2Ban#

在基于 Debian/Ubuntu 的系统中执行:

sudo apt update
sudo apt install fail2ban -y

在基于 RHEL/CentOS 的系统中执行:

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

配置文件管理原则#

Fail2Ban 默认配置文件为 /etc/fail2ban/jail.conf。为防止软件更新覆盖配置,禁止直接修改该文件。所有自定义配置应写入 /etc/fail2ban/jail.local

创建并编辑配置文件:

sudo touch /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local

标准配置方案#

将以下内容写入 /etc/fail2ban/jail.local

[DEFAULT]
# 基础封禁参数
bantime = 24h
findtime = 1h
maxretry = 3
# 启用阶梯式封禁(针对多次被封禁的 IP 延长封禁时间)
bantime.increment = true
bantime.factor = 1
bantime.maxtime = 5w
# 指定防火墙后端(推荐使用 nftables)
banaction = nftables-multiport
backend = systemd
[sshd]
enabled = true
# 指定实际使用的 SSH 端口
port = 4399
# 开启激进模式以捕获协议错误、预认证阶段断开等恶意探测
filter = sshd[mode=aggressive]

关键参数说明#

  • mode = aggressive:此模式不仅监控密码失败,还会监控密钥交换失败(kex_protocol_error)、连接重置(Connection reset by… [preauth])等行为。适用于已禁用密码登录、仅使用证书登录的服务器。
  • bantime.increment:开启后,如果同一 IP 重复触发封禁,封禁时间将按指数级增长,最高可达 bantime.maxtime
  • findtime = 1h:将监控窗口延长至 1 小时,用于捕获低频尝试的扫描脚本。

服务管理命令#

启动与重新加载#

# 启动服务并设置开机自启
sudo systemctl enable --now fail2ban
# 每次修改 jail.local 后重新加载配置
sudo systemctl restart fail2ban

查看状态#

# 查看 Fail2Ban 整体运行状态
fail2ban-client status
# 查看 SSH 监狱的具体封禁列表和统计
fail2ban-client status sshd

验证配置生效情况#

# 查询当前 sshd 监狱生效的 maxretry 值
fail2ban-client get sshd maxretry
# 查询当前 sshd 监狱生效的模式
fail2ban-client get sshd filter

手动操作#

# 手动封禁一个 IP
fail2ban-client set sshd banip <IP地址>
# 手动解封一个 IP
fail2ban-client set sshd unbanip <IP地址>

日志监控#

通过查看日志确认 Fail2Ban 是否正常识别并过滤恶意请求:

# 查看 Fail2Ban 运行日志
sudo tail -f /var/log/fail2ban.log
# 查看 SSH 登录尝试日志
sudo journalctl -u ssh -f
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

fail2ban
https://blog.085404.xyz/posts/fail2ban/
作者
Sun2ot
发布于
2026-01-17
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00