#!/usr/bin/env bash
# first-hour-init.sh — 上架首小時冪等初始化(Debian/Ubuntu)
# 冪等口徑:重復執行結果不變;失敗即停(set -e);全程日志 /var/log/first-hour-init.log
set -euo pipefail
LOG=/var/log/first-hour-init.log
exec >>"$LOG" 2>&1
echo "=== $(date -u +%FT%TZ) first-hour-init 開始 ==="
# ── 0. 前置檢查 ─────────────────────────────
[ "$(id -u)" = 0 ] || { echo "FATAL: 需要 root"; exit 1; }
[ -s /root/.ssh/authorized_keys ] || { echo "FATAL: 先配置 SSH 密鑰再運行(禁密碼前必須驗證密鑰可登入)"; exit 1; }
# ── 1. SSH 加固(drop-in 文件,存在即覆蓋=冪等)──
mkdir -p /etc/ssh/sshd_config.d
cat > /etc/ssh/sshd_config.d/99-hardening.conf <<'EOF'
PermitRootLogin prohibit-password
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
LoginGraceTime 20
EOF
sshd -t && (systemctl reload ssh 2>/dev/null || systemctl reload sshd)
# ── 2. 防火牆基線(先重置再聲明=冪等)─────────
if command -v ufw >/dev/null; then
ufw --force reset >/dev/null
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp comment 'ssh'
ufw allow 80/tcp comment 'http'
ufw allow 443/tcp comment 'https'
ufw --force enable
fi
# ── 3. fail2ban ─────────────────────────────
if command -v fail2ban-client >/dev/null; then
printf '[sshd]\nenabled = true\nmaxretry = 5\nfindtime = 600\nbantime = 3600\n' \
> /etc/fail2ban/jail.d/sshd.local
systemctl enable --now fail2ban
fi
# ── 4. 自動安全更新(只補丁不升版)────────────
if command -v apt-get >/dev/null && [ ! -d /etc/apt/apt.conf.d ]; then :; elif command -v apt-get >/dev/null; then
apt-get install -y unattended-upgrades >/dev/null
dpkg-reconfigure -f noninteractive unattended-upgrades >/dev/null || true
fi
# ── 5. 裝機基線採集(日後對照「變沒變」)───────
mkdir -p /var/log/baseline
{ echo "# baseline $(date -u +%FT%TZ)"; uname -a
lscpu | grep -E "Model name|^CPU\(s\)"; free -h; df -h /
ss -tlnp; ip -brief addr; } > "/var/log/baseline/boot-$(date +%F).txt"
timedatectl set-ntp true 2>/dev/null || true
echo "=== 完成:SSH/防火牆/fail2ban/更新/基線 五段就位 ==="
──────────────────────
【用法】scp 上傳後 bash first-hour-init.sh;跑完 ssh 新開終端驗證密鑰可登、密碼被拒。
【冪等驗證】再跑一遍,diff /etc/ssh/sshd_config.d/99-hardening.conf 應無變化、ufw 規則應無重復。
【擴展】業務棧(Nginx/DB)寫第二層腳本,兩層分開;改了 SSH 端口先改腳本第 2 段再執行。
【實測記錄】Ubuntu 22.04/24.04 LTS 實測通過;Debian 12 實測通過;RHEL 系需替換 apt→dnf、ufw→firewalld(結構不變)。