要在Linux上配置fail2ban以防止暴力破解攻击,可以按照以下步骤进行:
步骤计划
1.安装fail2ban:使用包管理器安装fail2ban。
2.配置fail2ban:编辑配置文件以设置监控和防护规则。
3.启动服务:启动fail2ban服务并确保其在系统启动时自动运行。
4.检查状态:验证fail2ban是否正常工作。
对于Debian/Ubuntu系统,使用以下命令:
sudo apt update
sudo apt install fail2ban
对于CentOS/RHEL系统,使用以下命令:
sudo yum install epel-release
sudo yum install fail2ban
创建本地配置文件:复制默认配置文件以进行自定义设置。
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
在文件中,您可以配置以下内容:
启用SSH保护:
sudo nano /etc/fail2ban/jail.local
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log # Debian/Ubuntu
# logpath = /var/log/secure # CentOS/RHEL
maxretry = 5
bantime = 3600
#单位S -1永久ban
其他服务的配置可以根据需要添加。
设置为开机自启:
sudo systemctl enable fail2ban --now
检查服务状态:
sudo systemctl status fail2ban
使用以下命令查看被禁止的IP地址和监控状态:
sudo fail2ban-client status
要查看特定监狱(如sshd)的状态:
sudo fail2ban-client status sshd
一键脚本
#!/bin/bash
# 检测操作系统
if [ -f /etc/debian_version ]; then
# Debian/Ubuntu 系统
echo "Detected Debian/Ubuntu system."
sudo apt update
sudo apt install -y fail2ban
# 创建本地配置文件
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
# 配置SSH保护
echo "[sshd]" | sudo tee -a /etc/fail2ban/jail.local
echo "enabled = true" | sudo tee -a /etc/fail2ban/jail.local
echo "port = ssh" | sudo tee -a /etc/fail2ban/jail.local
echo "filter = sshd" | sudo tee -a /etc/fail2ban/jail.local
echo "logpath = /var/log/auth.log" | sudo tee -a /etc/fail2ban/jail.local
echo "maxretry = 5" | sudo tee -a /etc/fail2ban/jail.local
echo "bantime = -1" | sudo tee -a /etc/fail2ban/jail.local
elif [ -f /etc/redhat-release ]; then
# CentOS/RHEL 系统
echo "Detected CentOS/RHEL system."
sudo yum install -y epel-release
sudo yum install -y fail2ban
# 创建本地配置文件
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
# 配置SSH保护
echo "[sshd]" | sudo tee -a /etc/fail2ban/jail.local
echo "enabled = true" | sudo tee -a /etc/fail2ban/jail.local
echo "port = ssh" | sudo tee -a /etc/fail2ban/jail.local
echo "filter = sshd" | sudo tee -a /etc/fail2ban/jail.local
echo "logpath = /var/log/secure" | sudo tee -a /etc/fail2ban/jail.local
echo "maxretry = 5" | sudo tee -a /etc/fail2ban/jail.local
echo "bantime = -1" | sudo tee -a /etc/fail2ban/jail.local
else
echo "Unsupported operating system."
exit 1
fi
# 启动并设置为开机自启
sudo systemctl enable --now fail2ban
echo "fail2ban has been installed and configured successfully."
将上述脚本保存为install_fail2ban.sh。
赋予执行权限:
chmod +x install_fail2ban.sh
./install_fail2ban.sh