#!/usr/bin/env bash # 检查当前环境是否有可用的 SSH 私钥,并测试到 Gitea 仓库的连通性 # 用法: bash check_ssh.sh [host] [port] # 默认: 47.121.181.112:222 set -euo pipefail HOST="${1:-47.121.181.112}" PORT="${2:-222}" USER="git" RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[0;33m' NC='\033[0m' # No Color echo "=== SSH 私钥检查 ===" # 1. 检查 ssh-agent 中是否有加载的密钥 if ssh-add -l 2>/dev/null | grep -q "."; then echo -e "${GREEN}[✓]${NC} ssh-agent 中有已加载的密钥" else echo -e "${YELLOW}[!]${NC} ssh-agent 中没有加载的密钥,将尝试使用 ~/.ssh/ 中的默认密钥" fi # 2. 检查常见私钥文件是否存在 FOUND_KEY=false for key_file in ~/.ssh/id_ed25519 ~/.ssh/id_rsa ~/.ssh/id_ecdsa ~/.ssh/id_dsa; do if [ -f "$key_file" ]; then echo -e "${GREEN}[✓]${NC} 找到私钥: $key_file" FOUND_KEY=true break fi done if [ "$FOUND_KEY" = false ]; then echo -e "${RED}[✗]${NC} 未找到任何默认 SSH 私钥(~/.ssh/id_ed25519, id_rsa, id_ecdsa, id_dsa)" echo "" echo "请生成一个新的 SSH 密钥:" echo " ssh-keygen -t ed25519 -C 'your_email@example.com'" echo "" echo "然后将公钥添加到 Gitea:" echo " cat ~/.ssh/id_ed25519.pub" echo " # 在 Gitea 的 Settings → SSH Keys 中添加" exit 1 fi # 3. 测试 SSH 连通性 echo "" echo "=== 测试 SSH 连通性 ===" echo "连接到 ${USER}@${HOST}:${PORT} ..." if ssh -o StrictHostKeyChecking=accept-new \ -o ConnectTimeout=10 \ -o BatchMode=yes \ -p "$PORT" \ "${USER}@${HOST}" 2>&1 | grep -qi "welcome\|gitea\|hello\|ssh"; then echo -e "${GREEN}[✓]${NC} SSH 连接成功" exit 0 else # ssh 返回非 0 但可能仍然成功(Gitea 会断开连接,返回码可能不为 0) # 尝试实际 git ls-remote 来验证 if git ls-remote "ssh://${USER}@${HOST}:${PORT}/wonder/docs.git" HEAD >/dev/null 2>&1; then echo -e "${GREEN}[✓]${NC} SSH 认证成功(可以访问仓库)" exit 0 else echo -e "${RED}[✗]${NC} SSH 连接失败" echo "" echo "可能的原因:" echo " 1. 私钥未添加到 Gitea" echo " 2. SSH 代理未运行" echo " 3. 网络不通" echo "" echo "请尝试:" echo " eval \$(ssh-agent -s)" echo " ssh-add ~/.ssh/id_ed25519" echo " ssh -p $PORT ${USER}@${HOST}" exit 1 fi fi