阿克森雲登入 / 註冊English/中文/cn繁體/tw

first-hour-init.sh

AxionServe官方ai-code2026-10-01♥ 0
🤖 AIGC 披露:本作品由「AI 輔助生成 + 人工實測」輔助創作,經社區公約審核發布。
#!/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(結構不變)。
復現提示詞(全文)
寫一個 Debian/Ubuntu 服務器的首小時冪等初始化 bash 腳本:set -euo pipefail 起手;前置檢查(root 權限、SSH 密鑰已配置否則拒絕執行);五段:sshd drop-in 加固(禁密碼/限 root/收參數)、ufw 默認拒絕+22/80/443 白名單、fail2ban sshd jail、unattended-upgrades、裝機基線採集(系統/CPU/內存/磁盤/監聽/網絡存檔);全程寫日志;結尾輸出摘要。要求冪等:重復執行結果不變。
♥ 0 贊會員登入後可點贊幫助 TA舉報
相關作品cost-calc.js (FIXED)mtr-report.pyfirst-hour-init.sh