← Back
Install fail2ban
Sets up an sshd jail that bans an address for an hour after five failures within ten minutes. Pairs well with the firewall script.
Root required
One-line run
curl -fsSL https://www.moiu.cn/scripts/fail2ban-install.sh | bashSource
#!/usr/bin/env bash
# 安装 fail2ban
#
# 装好后开一个 sshd 的 jail:10 分钟内失败 5 次就封 1 小时。
# 想让它直接调 ufw 封禁,先跑 ufw-firewall.sh 把 ufw 装好。
set -e
# 需要 root:下面的系统级改动都直接执行,不再逐条 sudo
if [ "$(id -u)" -ne 0 ]; then
echo '[!] 这个脚本需要 root 权限,请用 sudo 重新运行:'
echo ' curl -fsSL 脚本地址 | sudo bash'
echo ' 或已经下载到本地:sudo bash 本文件'
exit 1
fi
echo '====== 安装 fail2ban ======'
if ! command -v fail2ban-server >/dev/null 2>&1; then
if command -v apt-get >/dev/null 2>&1; then
apt-get update -qq
apt-get install -y fail2ban
elif command -v dnf >/dev/null 2>&1; then
dnf install -y fail2ban
else
echo '[!] 认不出包管理器(只支持 apt / dnf)'
exit 1
fi
fi
cat > /etc/fail2ban/jail.local <<'JAIL_EOF'
# 由 XiaoMo 脚本写入
[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5
[sshd]
enabled = true
JAIL_EOF
echo '[*] 已写入 /etc/fail2ban/jail.local'
systemctl enable --now fail2ban
systemctl restart fail2ban
echo ''
echo '====== 当前状态 ======'
fail2ban-client status 2>/dev/null || true
echo ''
fail2ban-client status sshd 2>/dev/null || true
