Fail2ban 通过分析日志,在检测到暴力破解或滥用行为时临时封禁 IP,可与 UFW 及 SSH 加固 配合使用。
前提条件
- Ubuntu/Debian 及
sudo - 需要保护的服务已运行(如
sshd、nginx)
安装
Bashsudo apt update && sudo apt install -y fail2ban sudo systemctl enable fail2ban sudo systemctl start fail2ban
基础配置
在 /etc/fail2ban/jail.d/ 下创建自定义配置,例如 local.conf:
INI1[DEFAULT] 2bantime = 1h 3findtime = 10m 4maxretry = 5 5ignoreip = 127.0.0.1/8 ::1 6 7[sshd] 8enabled = true 9port = ssh 10logpath = %(sshd_log)s 11backend = %(sshd_backend)s
若修改了 SSH 端口,将 port = ssh 改为实际端口(如 2222)。
Bashsudo systemctl restart fail2ban sudo fail2ban-client status sshd
Nginx 示例
INI[nginx-http-auth] enabled = true port = http,https logpath = /var/log/nginx/error.log
请按实际日志路径调整。
手动解封 IP
Bashsudo fail2ban-client set sshd unbanip 198.51.100.10
故障排除
- 无封禁:检查
enabled、logpath及服务是否记录失败登录。 - 误封自己:在
ignoreip中加入固定 IP,或通过云控制台解困。