Files
fnshell/setup-nas-poweroff.sh
2025-12-16 21:48:24 +08:00

66 lines
1.5 KiB
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
set -e
echo "== NAS SSH 远程关机初始化脚本 =="
echo "作者: wukongdaily"
echo "用途: 允许 OpenWrt 通过 SSH 安全关机 NAS"
echo
if [ "$EUID" -eq 0 ]; then
echo "❌ 请不要使用 root 运行此脚本"
exit 1
fi
USER_NAME="$(whoami)"
SYSTEMCTL_PATH="$(command -v systemctl)"
if [ -z "$SYSTEMCTL_PATH" ]; then
echo "❌ 未检测到 systemctl非 systemd 系统)"
exit 1
fi
# 自动检测可写家目录
TEST_DIR="$HOME"
if [ ! -w "$TEST_DIR" ]; then
echo "⚠ 当前 \$HOME ($HOME) 不可写,尝试使用 /vol1/1000"
TEST_DIR="/vol1/1000"
if [ ! -w "$TEST_DIR" ]; then
echo "❌ 没有可写目录,请手动设置 NAS_HOME 变量"
exit 1
fi
fi
NAS_HOME="$TEST_DIR"
echo "当前用户: $USER_NAME"
echo "systemctl: $SYSTEMCTL_PATH"
echo "将使用目录: $NAS_HOME"
echo
echo "将执行:"
echo " - 初始化 ~/.ssh 权限"
echo " - 配置 sudo 允许 poweroff"
echo
read -p "是否继续?[y/N]: " CONFIRM
[[ "$CONFIRM" =~ ^[Yy]$ ]] || exit 0
# SSH 目录
mkdir -p "$NAS_HOME/.ssh"
chmod 700 "$NAS_HOME/.ssh"
touch "$NAS_HOME/.ssh/authorized_keys"
chmod 600 "$NAS_HOME/.ssh/authorized_keys"
# sudo 规则
SUDO_RULE="$USER_NAME ALL=(root) NOPASSWD:$SYSTEMCTL_PATH poweroff"
if sudo grep -qF "$SUDO_RULE" /etc/sudoers; then
echo "✔ sudo 规则已存在"
else
echo "$SUDO_RULE" | sudo tee -a /etc/sudoers >/dev/null
echo "✔ sudo 规则已写入"
fi
echo
echo "🎉 初始化完成"
echo "测试命令:"
echo " sudo $SYSTEMCTL_PATH poweroff"