#!/usr/bin/env bash # Install Server Monitor as a systemd service. set -euo pipefail if [[ "${EUID}" -ne 0 ]]; then echo "请使用 root 运行:sudo ./install.sh" >&2 exit 1 fi if ! command -v systemctl >/dev/null 2>&1; then echo "未找到 systemctl,此脚本需要 systemd。" >&2 exit 1 fi if ! command -v python3 >/dev/null 2>&1; then echo "未找到 python3,请先安装 Python 3.8+。" >&2 exit 1 fi if ! python3 -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 8) else 1)'; then echo "Python 版本过低,需要 3.8 或更新版本。" >&2 exit 1 fi SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" TARGET_DIR="/opt/server-monitor" UNIT_PATH="/etc/systemd/system/server-monitor.service" ENV_PATH="/etc/server-monitor.env" for required in monitor.py servermon web deploy/server-monitor.service; do if [[ ! -e "${SOURCE_DIR}/${required}" ]]; then echo "安装文件不完整,缺少: ${SOURCE_DIR}/${required}" >&2 echo "请在完整仓库目录中运行安装脚本。" >&2 exit 1 fi done install -d -m 0755 "${TARGET_DIR}" TARGET_DIR="$(cd "${TARGET_DIR}" && pwd -P)" if [[ "${SOURCE_DIR}" == "${TARGET_DIR}" ]]; then # The repository is already installed at /opt/server-monitor (a common # deployment). Copying a file onto itself would make install(1) fail and # deleting the target directories would delete the source we are running # from, so only install the systemd unit in this case. echo "当前目录就是安装目录 ${TARGET_DIR},跳过文件复制。" else install -m 0755 "${SOURCE_DIR}/monitor.py" "${TARGET_DIR}/monitor.py" rm -rf "${TARGET_DIR}/servermon" "${TARGET_DIR}/web" cp -a "${SOURCE_DIR}/servermon" "${TARGET_DIR}/servermon" cp -a "${SOURCE_DIR}/web" "${TARGET_DIR}/web" install -m 0644 "${SOURCE_DIR}/README.md" "${TARGET_DIR}/README.md" fi if [[ ! -f "${ENV_PATH}" ]]; then cat >"${ENV_PATH}" <<'EOF' # Server Monitor 环境变量(可选) # 取消下一行注释并改成自己的凭据即可启用 HTTP Basic 认证: # SERVER_MONITOR_AUTH=admin:change-me EOF chmod 0600 "${ENV_PATH}" fi install -m 0644 "${SOURCE_DIR}/deploy/server-monitor.service" "${UNIT_PATH}" systemctl daemon-reload systemctl enable --now server-monitor.service systemctl restart server-monitor.service echo echo "Server Monitor 已安装并启动。" echo " 访问: http://<服务器IP>:8787/" echo " 状态: systemctl status server-monitor --no-pager" echo " 日志: journalctl -u server-monitor -f" echo " 认证: 编辑 ${ENV_PATH} 后 systemctl restart server-monitor" echo systemctl --no-pager --lines=0 status server-monitor.service || true