确认使用的是nftables还是iptables
使用以下命令:
sudo systemctl status iptables
如果输出Unit iptables.service could not be found则没有使用iptables
使用以下命令:
sudo systemctl status nftables
如果正常输出,则使用的是nftables
nftables和iptables的区别本文不再阐述,有兴趣的同学可以自行百度学习。
确认默认支持的 banaction 类型
- 查看现有动作文件
Fail2Ban 的 banaction 配置需与底层防火墙工具匹配。若系统使用 nftables,需检查 /etc/fail2ban/action.d/ 目录下是否存在适配的配置文件(如 nftables.conf 或 nftables-multiport.conf)。
配置 banaction 为 nftables 动作
- 修改 jail.local 文件
在 /etc/fail2ban/jail.local 的 [DEFAULT] 或具体服务的配置区块中,指定 banaction 为 nftables 相关动作。例如:
[DEFAULT]
banaction = nftables-multiport # 使用 nftables 多端口封锁
若需限制具体协议(如仅 IPv4),可配置为 banaction = nftables-ipv437。
自定义 nftables 动作(可选)
- 手动调整动作脚本
若默认动作不满足需求,可复制现有配置文件并修改命令为 nft。例如:
cp /etc/fail2ban/action.d/iptables-multiport.conf /etc/fail2ban/action.d/nftables-custom.conf
修改 nftables-custom.conf 中的 actionban 和 actionunban 字段,替换 iptables 命令为 nft 语法。
示例调整片段:
actionban = nft add rule inet filter fail2ban-<name> ip saddr <ip> counter drop
actionunban = nft delete rule inet filter fail2ban-<name> handle <rule-handle>
验证与测试
重启服务并触发封锁
重启 Fail2Ban 使配置生效:
systemctl restart fail2ban
通过模拟攻击(如多次 SSH 登录失败)触发封锁,检查 nftables 规则是否生效:
nft list ruleset | grep <被封IP>
排查日志
若未生效,查看 Fail2Ban 日志定位问题:
tail -f /var/log/fail2ban.log
关注是否出现 nft 命令执行错误或权限问题。
兼容性说明
- 系统版本影响:
CentOS/RHEL 8+ 及 Debian 10+ 默认使用 nftables,需确保 Fail2Ban 版本 ≥ 0.10 以原生支持 nftables 动作37。 - 混合环境处理:
若系统同时存在 iptables 和 nftables(如兼容层模式),建议优先使用 nftables 动作以避免规则冲突3。
通过以上配置,Fail2Ban 可正确通过 nftables 实现 IP 封锁。若需更复杂规则(如基于集合的动态管理),可参考 nftables 文档扩展自定义动作。
fail2ban基本命令
查看ssh配置
fail2ban-client status sshd
重启fail2fan
sudo systemctl restart fail2ban