Files
fnshell/generate_ssh_key.sh

70 lines
2.0 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
# ======================================================
# OpenWrt SSH 公钥生成脚本
# 自动检查并安装 ssh-keygen
# ======================================================
KEY_NAME="id_dropbear"
HIDDEN_DIR="$HOME/.ssh"
PUBLIC_DIR="$HOME/ssh_public" # 普通目录,方便用户下载
PRIV_KEY="$HIDDEN_DIR/$KEY_NAME"
PUB_KEY="$HIDDEN_DIR/$KEY_NAME.pub"
PUB_KEY_COPY="$PUBLIC_DIR/$KEY_NAME.pub"
# ------------------------------------------------------
# 检查 ssh-keygen 是否存在
# ------------------------------------------------------
if ! command -v ssh-keygen >/dev/null 2>&1; then
echo "⚠️ 未检测到 ssh-keygen尝试安装 openssh-keygen ..."
# opkg 安装阶段不能让 set -e 直接中断
set +e
opkg update
opkg install openssh-keygen
RET=$?
set -e
if [ $RET -ne 0 ]; then
echo "❌ openssh-keygen 安装失败"
echo "请检查网络或软件源是否正常"
exit 1
fi
echo "✅ openssh-keygen 安装完成"
fi
# ------------------------------------------------------
# 创建目录
# ------------------------------------------------------
mkdir -p "$HIDDEN_DIR"
chmod 700 "$HIDDEN_DIR"
mkdir -p "$PUBLIC_DIR"
chmod 755 "$PUBLIC_DIR"
# ------------------------------------------------------
# 生成密钥
# ------------------------------------------------------
if [ ! -f "$PRIV_KEY" ]; then
echo "🔐 未发现 SSH 密钥开始生成ed25519..."
ssh-keygen -t ed25519 -f "$PRIV_KEY" -N ""
else
echo " 已存在 SSH 密钥,跳过生成"
echo "私钥路径: $PRIV_KEY"
fi
# ------------------------------------------------------
# 复制公钥到普通目录,方便用户下载
# ------------------------------------------------------
cp -f "$PUB_KEY" "$PUB_KEY_COPY"
chmod 644 "$PUB_KEY_COPY"
# ------------------------------------------------------
# 输出结果
# ------------------------------------------------------
echo "✅ SSH 公钥准备完成"
echo "隐藏目录公钥: $PUB_KEY"
echo "可下载公钥副本: $PUB_KEY_COPY"