Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 安装配置 Fail2Ban 防暴力破解:SSH 保护、邮件通知与日志轮转

編輯:關於 Linux

Fail2Ban 监控日志文件,匹配失败特征(如 SSH 登录失败)后动态封禁攻击 IP(iptables/hosts.deny/shorewall)。本文记录 Python 依赖、Fail2Ban 安装、日志轮转、核心配置文件结构与 SSH 防护实战。

一、安装 Python 2.7.3(系统自带版本过旧时)

cd /tmp
wget https://python.org/ftp/python/2.7.3/Python-2.7.3.tgz
tar xzf Python-2.7.3.tgz
cd Python-2.7.3
./configure && make && make install
rm -f /usr/bin/python
ln -s /tmp/Python-2.7.3/python /usr/bin/python

现代系统建议直接使用系统自带 Python 3 + pip install fail2ban。

二、安装 Fail2Ban 0.8.6

cd /tmp
wget https://github.com/downloads/fail2ban/fail2ban/fail2ban_0.8.6.orig.tar.gz
tar xzf fail2ban_0.8.6.orig.tar.gz
cd fail2ban-*
python setup.py install

# 注册 SysVinit 服务
cp files/RedHat-initd /etc/init.d/fail2ban
chmod 755 /etc/init.d/fail2ban
chkconfig --add fail2ban
chkconfig fail2ban on

三、配置日志轮转 (/etc/logrotate.d/fail2ban)

/var/log/fail2ban.log {
    weekly
    rotate 7
    missingok
    compress
    postrotate
        /etc/init.d/fail2ban restart >/dev/null 2>&1 || true
    endscript
}

四、核心配置目录结构 (/etc/fail2ban/)

/etc/fail2ban/
├── action.d/          # 封禁动作:iptables、hostsdeny、shorewall、mail
├── fail2ban.conf      # 主配置:日志级别、socket、pid 文件
├── fail2ban.local     # 本地覆盖主配置
├── filter.d/          # 正则过滤器:sshd、apache、vsftpd 等
├── jail.conf          # 监狱定义:filter+action+参数组合
└── jail.local         # 本地覆盖监狱配置(推荐修改此文件)

五、SSH 防护实战配置 (jail.local)

[sshd]
enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/secure
maxretry = 3
bantime  = 3600
findtime = 600
action   = iptables-multiport[name=sshd, port="ssh", protocol=tcp]
           sendmail-whois[name=sshd, dest=admin@example.com, sender=fail2ban@example.com]
# 启用后:service fail2ban restart

Fail2Ban 配置目录结构示意图

Fail2Ban 通过 filter.d 正则匹配日志、action.d 执行封禁动作、jail.* 组合策略,配合 logrotate 管理日志,是 Linux 服务器防暴力破解的标准化组件。生产环境建议结合 firewalld rich rules 或 nftables 实现更高性能封禁。

Copyright © Windows教程網 All Rights Reserved