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

61 lines
1.5 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
# ===== 阶段二:推送公钥到飞牛 NAS =====
echo "== [2/2] 推送公钥到飞牛 NAS =="
echo "⚠️ 如果是首次登录,可能需要输入飞牛用户密码并确认 host key"
# 检测远程 HOME 并创建 ~/.ssh第一次会要求密码
ssh -t "$USER_NAME@$NAS_IP" << 'EOF'
set -e
# 使用远程真实 HOME飞牛可能不是 /home/username
HOME_DIR="$HOME"
SSH_DIR="$HOME_DIR/.ssh"
AUTH_KEYS="$SSH_DIR/authorized_keys"
mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"
# 确保 authorized_keys 文件存在
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"