#!/bin/bash # install.sh — 部署健康监控到服务器 # # 用法(在服务器上 root 跑): # cd /tmp && tar xzf health-monitor.tar.gz && cd health-monitor && bash install.sh # # 前置条件: # 1. /etc/health-monitor.env 已存在并填好 QQ_AUTH_CODE(参考 health-monitor.env.example) set -e if [ "$(id -u)" -ne 0 ]; then echo "必须 root 运行" >&2 exit 1 fi SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" # 1. 凭证 if [ ! -f /etc/health-monitor.env ]; then echo "ERROR: /etc/health-monitor.env 不存在,请按以下步骤创建:" >&2 echo " cp $SCRIPT_DIR/health-monitor.env.example /etc/health-monitor.env" >&2 echo " vim /etc/health-monitor.env # 填入 QQ_AUTH_CODE" >&2 echo " chmod 600 /etc/health-monitor.env" >&2 exit 1 fi chmod 600 /etc/health-monitor.env # 检查 QQ_AUTH_CODE 是否还是占位符 if grep -q 'QQ_AUTH_CODE=把你的' /etc/health-monitor.env; then echo "ERROR: /etc/health-monitor.env 还是占位符,请填入真实 QQ 邮箱授权码" >&2 exit 1 fi # 2. 主脚本 install -m 755 "$SCRIPT_DIR/health-monitor.sh" /usr/local/bin/health-monitor.sh install -m 755 "$SCRIPT_DIR/health-send-mail.py" /usr/local/bin/health-send-mail.py install -m 755 "$SCRIPT_DIR/health-push.py" /usr/local/bin/health-push.py # 3. 状态目录 mkdir -p /var/lib/health-monitor /var/log # 4. cron (每 5 分钟,错开 :03 避开整点) cat > /etc/cron.d/health-monitor <<'EOF' # 健康监控:每 5 分钟(错开 :03)检测 /health + /api/navigation/config # 失败连续 2 次才告警,同一故障 30 分钟内只发一次 SHELL=/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin MAILTO="" 3,8,13,18,23,28,33,38,43,48,53,58 * * * * root /usr/local/bin/health-monitor.sh >> /var/log/health-monitor.log 2>&1 EOF chmod 644 /etc/cron.d/health-monitor # 5. 立即跑一次 dry-run(用真实凭证)验证通路 echo "" echo "=== 安装完成,立即跑一次 smoke test ===" bash /usr/local/bin/health-monitor.sh echo "" echo "退出码: $?" echo "日志: tail -20 /var/log/health-monitor.log" echo "" echo "查看 cron: cat /etc/cron.d/health-monitor" echo "手动触发: bash /usr/local/bin/health-monitor.sh" echo "测试告警: pm2 stop server && bash /usr/local/bin/health-monitor.sh"