安装Fail2ban
1. 下载
wget https://raw.githubusercontent.com/FunctionClub/Fail2ban/master/fail2ban.sh
2. 安装
bash fail2ban.sh
安装过程:
- 第一步选择是否修改SSH端口;
- 第二步输入最多尝试输入SSH连接密码的次数。(2-10次)
- 第三步输入每个恶意IP的封禁时间(Default: 24h)
3. 修改配置
vim /etc/fail2ban/jail.local
修改为:
[DEFAULT] ignoreip = 127.0.0.1 bantime = 86400 maxretry = 3 findtime = 1800 [ssh-iptables] enabled = true filter = sshd action = iptables[name=SSH, port=ssh, protocol=tcp] logpath = /var/log/auth.log maxretry = 3 findtime = 3600 bantime = 86400
然后重载配置:
sudo fail2ban-client reload
参考:Ubuntu配置Fail2Ban防止SSH暴力破解与邮件预警 - 鲁娜的博客 | Luna's Blog (dulunar.github.io)
禁用后解禁
fail2ban-client set ssh-iptables unbanip 你的ip
fail2ban-client set sshd unbanip 你的ip
安装邮箱通知(可选)
1. 安装heirloom-mailx
进入 /etc/apt/sources.list.d 新建文件 mailx.list ,内容:
deb http://cz.archive.ubuntu.com/ubuntu xenial main universe
更新软件源并安装:
apt-get update
apt install heirloom-mailx
2. 安装mailutils
apt-get install mailutils
3. 修改/etc/s-nail.rc 配置,末尾追加:
set from="你的邮箱@qq.com" set smtp="smtps://smtp.qq.com:465" set smtp-auth-user="你的邮箱@qq.com" set smtp-auth-password="邮箱授权码,不是密码" set smtp-auth=login 如果你使用的有些不需要ssl,加上:
set ssl-verify=ignore
4. 测试发送邮箱:
echo "内容"|s-nail -s "测试发送" 任意一个邮箱来接收邮件@qq.com
5. 修改Fail2ban配置:
vim /etc/fail2ban/jail.local
[DEFAULT] ignoreip = 127.0.0.1 bantime = 86400 maxretry = 3 findtime = 1800 mail-whois[name=SSH, dest=liohuang@dingtalk.com, sender=gxrcsc-bigdata@yandex.com] [ssh-iptables] enabled = true filter = sshd action = iptables[name=SSH, port=ssh, protocol=tcp] logpath = /var/log/auth.log maxretry = 3 findtime = 3600 bantime = 86400
重新载入配置:
sudo fail2ban-client reload
下班!