Git SSH Agent Forwarding
Git 使用 SSH(不在远端保存私钥):Windows → 远端配置步骤
目标:远端执行 git clone/fetch/push 时,通过 SSH Agent Forwarding 使用你 Windows 本机的 SSH key;远端不落地私钥文件。
1) Windows 本机:启用系统 OpenSSH 的 ssh-agent 并加载 Key
1.1 启用并启动 ssh-agent(管理员 PowerShell)
Get-Service ssh-agent | Set-Service -StartupType Automatic
Start-Service ssh-agent
Get-Service ssh-agent
1.2 加载私钥到 agent(普通 PowerShell)
ssh-add $env:USERPROFILE\.ssh\id_ed25519
ssh-add -l
要求:ssh-add -l 能列出至少一把 key(不要显示 The agent has no identities.)。
1.3 确认使用的是 Windows 系统 OpenSSH(避免 Git Bash 的 ssh/agent 混用)
where ssh
where ssh-add
ssh -V
期望优先出现:
C:\Windows\System32\OpenSSH\ssh.exeC:\Windows\System32\OpenSSH\ssh-add.exe
2) GitHub:添加公钥
把公钥添加到 GitHub:Settings → SSH and GPG keys → New SSH key
本机查看公钥内容:
type $env:USERPROFILE\.ssh\id_ed25519.pub
3) 客户端:使用系统 OpenSSH,并开启 SSH Agent Forwarding
在你用于连接远端的 SSH 客户端/工具中:
- 选择使用 OpenSSH
- 开启 Forward SSH agent / Agent forwarding
- 将 OpenSSH 工具路径指定为系统 ssh(建议写死完整路径):
C:\Windows\System32\OpenSSH\ssh.exe
- 断开并重新连接远端(让新会话生效)
4) 远端:验证转发是否生效
登录远端后执行:
echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
ssh-add -l
期望:
SSH_AUTH_SOCK有值(非空)ssh-add -l能列出 key(不是The agent has no identities.)
5) 远端:验证 GitHub SSH 认证
ssh -T git@github.com
失败时用详细日志定位:
ssh -vT git@github.com
6) 仓库:确保 remote URL 是 SSH(不是 HTTPS)
git remote -v
如果是 HTTPS,改成 SSH:
git remote set-url origin git@github.com:OWNER/REPO.git
常见故障速查
A) 远端 ssh-add -l 显示 The agent has no identities.
- Windows 本机系统 ssh-agent 没加载 key:回到 1.2 重新
ssh-add ... - 客户端未实际使用系统 OpenSSH:回到 3 确认路径为
C:\Windows\System32\OpenSSH\ssh.exe并重连
B) 远端能列出 key,但仍 Permission denied (publickey)
- GitHub 未添加对应公钥:回到 2
- 仓库 remote 不是 SSH:回到 6
- 用
ssh -vT git@github.com看是否有Offering public key,以及哪把 key 被提供/拒绝