安装
sudo
sudo yum install fail2ban -y
Fail2Ban的默认配置文件在/etc/fail2ban/jail.conf,但不建议直接编辑这个文件。/etc/fail2ban/jail.local的优先级默认更高,无需指定路径。
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo vim /etc/fail2ban/jail.local
[api-worktool]
enabled = true
port = http,https
filter = nginx-errors
logpath = /www/wwwlogs/api.worktool.ymdyes.cn.log
maxretry = 10
[site2]
enabled = true
port = http,https
filter = nginx-errors
logpath = /www/wwwlogs/site2.example.com.log
maxretry = 3
创建或编辑过滤器文件 /etc/fail2ban/filter.d/nginx-errors.conf,添4xx、5xx错误码
sudo vim /etc/fail2ban/filter.d/nginx-errors.conf
[Definition]
failregex = ^<HOST> -.* "(GET|POST|PUT|DELETE|HEAD).*HTTP/.*" (4\d{2}|5\d{2})
重启fail2ban生效
sudo systemctl enable fail2ban
sudo systemctl restart fail2ban
检查和测试
sudo fail2ban-client status
sudo fail2ban-client status api-worktool
sudo fail2ban-client status site2
sudo fail2ban-client -d
Fail2Ban会使用iptables来禁止IP地址。确保你的防火墙允许Fail2Ban添加规则。(缺省)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload