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

59 lines
1.3 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 =="
# 第一次连接:创建 ~/.ssh 并设置权限(不使用 sudo不假设 /home
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
# 写入公钥(真正推 key 的关键一步)
cat "$PUB_KEY" | ssh "$USER_NAME@$NAS_IP" \
"cat >> ~/.ssh/authorized_keys"
echo "✅ SSH 公钥已成功推送:$USER_NAME@$NAS_IP"
echo " 以后可直接免密登录ssh $USER_NAME@$NAS_IP"