目录(本文ChatGPT生成,仅供参考)
1. 安装 Fail2ban
在 Debian/ubuntu 系统上运行以下命令安装 Fail2ban:
sudo apt update
sudo apt install fail2ban -y
在 CentOS 上安装 Fail2ban 需要使用yum,没有成功试试 dnf(FedoraOS):
sudo dnf install epel-release -y
sudo dnf install fail2ban fail2ban-firewalld -y
2. 配置 Fail2ban
Fail2ban 的主配置文件是 /etc/fail2ban/jail.conf,但为了避免升级覆盖,建议创建本地配置文件 /etc/fail2ban/jail.local。
创建或编辑 /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
添加以下配置内容:
[DEFAULT]
# 禁封时间,秒为单位 (600秒 = 10分钟)
bantime = 600
# 尝试次数
maxretry = 5
# 日志文件格式 (自动检测)
logencoding = auto
# 忽略的IP列表 (例如你的本地IP地址)
ignoreip = 127.0.0.1/8 ::1 你的IP地址
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 5
3. 为 Nginx 配置 Fail2ban 过滤器
Fail2ban 自带 Nginx 的过滤器文件 /etc/fail2ban/filter.d/nginx-http-auth.conf。如果需要针对特定攻击(如 404 攻击、暴力破解),可以自定义过滤器。
示例:创建一个自定义过滤器 /etc/fail2ban/filter.d/nginx-limit-req.conf
sudo nano /etc/fail2ban/filter.d/nginx-limit-req.conf
内容示例(不完整,请勿使用):
[Definition]
failregex =
ignoreregex =
在 jail.local 中添加规则:
[nginx-limit-req]
enabled = true
port = http,https
filter = nginx-limit-req
logpath = /var/log/nginx/access.log
maxretry = 10
4. 重启服务以应用配置
CentOS配置防火墙
CentOS 使用 firewalld,需要确保它已启用并为 Fail2ban 添加支持:
sudo systemctl enable firewalld --now
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
Fail2ban 会自动使用 firewalld 管理封禁 IP 的规则。
保存配置后,重启 Fail2ban:
sudo systemctl restart fail2ban
sudo systemctl enable fail2ban
5. 检查运行状态
查看 Fail2ban 的状态以确保其正常运行:
sudo systemctl status fail2ban
查看激活的 Jail:
sudo fail2ban-client status
查看特定 Jail 的状态(例如 SSH):
sudo fail2ban-client status sshd
6. 测试规则
可以尝试用错误的密码登录 SSH 或者发出非法 Nginx 请求,查看是否会触发规则并被封禁。Fail2ban 的日志记录在 /var/log/fail2ban.log。
查看 Fail2ban 日志:
sudo tail -f /var/log/fail2ban.log
你可以通过查看 Fail2ban 的状态来确认是否有 IP 被封禁:
sudo fail2ban-client status
如果需要解除封禁,执行以下命令:
sudo fail2ban-client unban <IP_ADDRESS>
完成后,Fail2ban 将自动保护你的服务器免受常见的 SSH 和 Nginx 攻击。如果有其他需求,可以进一步自定义规则。
补充
站长工具端口扫描80,8443(https )关闭
检查防火墙和安全组设置
Fail2ban 或防火墙可能封禁了这些端口。首先检查防火墙状态:
sudo firewall-cmd --state
如果返回 “running”,则说明防火墙处于启用状态。检查是否允许 HTTP 和 HTTPS 流量通过防火墙:
sudo firewall-cmd --list-all
如果 80 和 8443 端口没有出现在允许的服务列表中,执行以下命令来允许它们:
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
如果你自定义了端口(如 8443),则需要手动添加:
sudo firewall-cmd --permanent --add-port=8443/tcp
sudo firewall-cmd --reload