Files
fnshell/push-sshkey-to-fnos.sh
2025-12-24 11:33:22 +08:00

67 lines
1.7 KiB
Bash
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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/sh
set -e
# ===== 参数 =====
USER_NAME="$1"
NAS_IP="$2"
KEY_DIR="/root/.ssh"
KEY_NAME="id_dropbear"
PRIV_KEY="$KEY_DIR/$KEY_NAME"
PUB_KEY="$KEY_DIR/$KEY_NAME.pub"
# ===== 参数检查 =====
if [ -z "$USER_NAME" ] || [ -z "$NAS_IP" ]; then
echo "用法: $0 <飞牛用户名> <飞牛IP>"
exit 1
fi
# ===== 阶段一:在 OpenWrt 上生成 SSH 密钥 =====
echo "== [1/2] 检查并生成 SSH 密钥 =="
if [ ! -d "$KEY_DIR" ]; then
mkdir -p "$KEY_DIR"
chmod 700 "$KEY_DIR"
fi
if [ ! -f "$PRIV_KEY" ]; then
echo "未发现 SSH 密钥开始生成ed25519..."
ssh-keygen -t ed25519 -f "$PRIV_KEY" -N ""
else
echo "已存在 SSH 密钥,跳过生成"
fi
# ===== 阶段二:检测远程是否能免密,首次登录提示手动输入密码 =====
echo "== [2/2] 推送公钥到飞牛 NAS =="
# 尝试用公钥免密登录
ssh -o BatchMode=yes "$USER_NAME@$NAS_IP" "echo '免密测试成功'" >/dev/null 2>&1
if [ $? -ne 0 ]; then
echo "⚠️ 检测到首次登录,需手动输入密码并确认 host key"
echo "请在提示时输入密码,完成一次手动登录,然后再运行脚本即可实现免密"
echo "你可以先运行: ssh $USER_NAME@$NAS_IP"
exit 1
fi
# 远程操作:创建 .ssh 目录及权限
ssh "$USER_NAME@$NAS_IP" << 'EOF'
set -e
# 使用远程真实 HOME
HOME_DIR="$HOME"
SSH_DIR="$HOME_DIR/.ssh"
AUTH_KEYS="$SSH_DIR/authorized_keys"
mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"
touch "$AUTH_KEYS"
chmod 600 "$AUTH_KEYS"
EOF
# 推送公钥到远程 authorized_keys
cat "$PUB_KEY" | ssh "$USER_NAME@$NAS_IP" "cat >> ~/.ssh/authorized_keys"
echo "✅ SSH 公钥已成功推送:$USER_NAME@$NAS_IP"
echo " 以后可直接免密登录ssh $USER_NAME@$NAS_IP"