方案一:修改 Git 全局配置(最简单)
# 1. 设置 Git 全局使用 SSH 代替 HTTPS
git config --global url."[email protected]:".insteadOf "https://github.com/"
# 2. 设置 SSH 命令使用您的密钥
git config --global core.sshCommand "ssh -i %USERPROFILE%\.ssh\id_ed25519"
# 3. 验证配置
git config --global --list | findstr "insteadof|sshCommand"
优点:配置简单,一键完成 缺点:所有仓库使用同一密钥
方案二:创建 SSH 配置文件(最推荐)
- 创建或编辑 SSH 配置文件:text 文件位置
C:\Users\你的用户名\.ssh\config - 添加以下内容:
# GitHub Host
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
PreferredAuthentications publickey
# 可选:为不同 GitHub 账户配置不同密钥
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/work_key
- 设置文件权限(在 Git Bash 中):
chmod 600 ~/.ssh/config
优点:灵活,支持多账户,符合 SSH 标准
方案三:Windows OpenSSH 服务(最稳定)
按 Win+X 选择管理员 PowerShell。
# 以管理员身份运行 PowerShell
# 1. 启用 SSH-Agent 服务
Set-Service ssh-agent -StartupType Automatic
# 2. 启动服务
Start-Service ssh-agent
# 3. 添加密钥到代理
ssh-add $HOME\.ssh\id_ed25519
# 4. 检查已加载的密钥
ssh-add -l
优点:系统级服务,重启后自动加载密钥
第四部分:验证配置是否成功
4.1 基础测试
# 测试 SSH 连接
ssh -T [email protected]
预期输出:
Hi 用户名! You've successfully authenticated, but GitHub does not provide shell access.
4.2 详细诊断
创建诊断脚本 check_ssh.bat:
@echo off
echo ===== SSH 配置诊断工具 =====
echo.
echo [1] 检查密钥文件...
if exist "%USERPROFILE%\.ssh\id_ed25519" (
echo ✓ 找到私钥文件
) else (
echo ✗ 未找到私钥文件,请先生成 SSH 密钥
)
echo.
echo [2] 检查 SSH 配置文件...
if exist "%USERPROFILE%\.ssh\config" (
type "%USERPROFILE%\.ssh\config"
echo.
) else (
echo ℹ 未找到 config 文件,将使用默认配置
)
echo
[3] 测试 GitHub 连接...
ssh -T [email protected] 2>&1 | findstr "successfully" >nul
if %errorlevel%==0 (
echo ✓ SSH 连接测试成功
) else (
echo ✗ SSH 连接测试失败
echo 请检查:1.公钥是否添加到 GitHub 2.网络连接
)
echo.
echo [4] 测试 Git 操作...
echo 正在克隆测试仓库...
git clone [email protected]:github/gitignore.git ssh-test-temp --depth=1 2>nul
if exist "ssh-test-temp" (
echo ✓ Git 克隆测试成功
rmdir /s /q ssh-test-temp 2>nul
) else (
echo ✗ Git 克隆测试失败
)
echo.
echo ===== 诊断完成 =====
pause

