使用Git for Windows推送代码时遭遇permission denied(publickey)问题求助
Git for Windows SSH连接Git远程仓库失败问题排查与解决
问题背景
- Windows系统,安装Git for Windows 2.40.0.windows.1
- 已生成非默认路径且带密码短语的SSH密钥对,公钥已添加至GitHub、GitLab个人资料
- SSH Agent服务已配置并运行,私钥已通过
ssh-add添加(Get-Service ssh-agent确认服务正常,ssh-add.exe -l显示密钥已加载) - 执行官方认证命令
ssh -T git@github.com可成功通过,但添加SSH远程地址后执行git push时持续报错,且GitLab也出现相同问题;Linux环境下无此异常,判定为Git for Windows或本地配置问题
报错信息
PS > git push origin main git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
排查与解决步骤
1. 统一Git使用的SSH客户端
Git for Windows可能同时兼容自带OpenSSH和Windows系统自带OpenSSH,两者环境变量和配置不共享,需明确指定Git使用的SSH路径:
- 查看当前Git的SSH命令配置:
git config --global core.sshCommand - 若返回空值,根据实际情况设置:
- 使用Git自带的OpenSSH:
git config --global core.sshCommand "'C:/Program Files/Git/usr/bin/ssh.exe'" - 使用Windows系统自带的OpenSSH:
git config --global core.sshCommand "'C:/Windows/System32/OpenSSH/ssh.exe'"
- 使用Git自带的OpenSSH:
2. 配置SSH Config文件指定密钥路径
由于密钥不在默认~/.ssh/id_rsa路径,需创建~/.ssh/config文件(Windows对应路径为C:\Users\<你的用户名>\.ssh\config),添加主机绑定配置:
Host github.com HostName github.com User git IdentityFile C:/path/to/your/private_key # 替换为你的私钥实际路径,使用正斜杠 IdentitiesOnly yes Host gitlab.com HostName gitlab.com User git IdentityFile C:/path/to/your/private_key IdentitiesOnly yes
IdentitiesOnly yes:强制SSH仅使用指定密钥,避免尝试其他无关密钥导致认证失败- 权限修正:右键config文件→属性→安全→高级,设置仅当前用户拥有读取权限,删除其他用户的权限(Windows对SSH配置文件权限敏感,过宽权限会导致密钥被拒绝加载)
3. 确保Git环境与SSH Agent共享密钥
Git Bash的环境可能和PowerShell的SSH Agent上下文不互通,尝试在Git Bash中重新加载密钥:
ssh-add /path/to/your/private_key
加载完成后在Git Bash中执行git push测试。
4. 开启SSH调试日志获取详细信息
若以上步骤无效,通过设置环境变量开启SSH调试日志,定位具体错误环节:
- PowerShell中执行:
$env:GIT_SSH_COMMAND = "ssh -vvv" - 再执行
git push origin main,此时会输出详细的SSH认证流程日志,可从中查看密钥加载、认证请求的具体细节。
额外注意事项
- 私钥文件权限需严格控制:Windows下私钥文件仅允许当前用户读取,禁止其他用户拥有任何权限
- 若使用WSL,注意区分Windows与WSL的
.ssh目录,两者配置相互独立
内容的提问来源于stack exchange,提问作者Chippy
相关产品推荐
相关产品推荐

