首页 > 解决方案 > 来自 Visual Studio Code 和 Visual Studio(但不是 Git Bash)的“权限被拒绝”错误

问题描述

使用运行 Windows 10 的新工作笔记本电脑,我安装gitVisual Studio CodeVisual Studio 2019. 在从我的个人 git 存储库(托管在github)中对代码进行一些测试更改后,我正在尝试提交这些更改并将其推送到远程存储库。

我可以从执行所有StageCommit操作。但在 Git Gui、VS Code 和 VS 2019 中,两者都可以正常工作,但会失败并显示错误消息。PushGit BashStageCommitPush

对于 VS Code,错误是:

git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

对于 VS 2019,错误类似:

git@github.com: Permission denied (publickey).
Error encountered while pushing to the remote repository: Git failed with a fatal error.
Could not read from remote repository.

我该如何解决这个问题?

更新

@DaemonPainter 的评论有助于找到答案。我的私人 SSH 密钥文件被命名id_rsa_githubid_rsa_github.pub. Visual Studio 2019、Code 和 Git Gui 都希望这些被命名id_rsaid_rsa.pub.

解决方案是添加一个config文件,%HOMEPATH%\.ssh其内容类似于:

host github.com
 HostName github.com
 IdentityFile ~/.ssh/id_rsa_github

进行更改后,git push可以在 Git Bash、Gut Gui、VS Code 和 Visual Studio 中使用。

标签: gitvisual-studio-codevisual-studio-2019

解决方案


正如@DaemonPainter 指出的那样,一种可能性是缺少 SSH 身份和密钥。对于这个问题,这个描述如何添加 SSH 密钥的答案可能会很有趣。

我的问题原来是 SSH 密钥文件的命名。默认情况下,这些文件位于%HOMEPATH%\.ssh文件名id_rsaid_rsa.pub. 开发人员工具,例如Visual Studio 2019, 并Git Gui期望使用该命名约定。

由于我的文件是用于个人 git 存储库的Github,因此我命名了 SSH 密钥文件id_rsa_github/.pub。在%HOMEPATH%\.bashrc中,添加了以下行(最初在另一台 PC 上配置并复制过来):

# Start ssh-agent to allow git to be used
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa_github

这就解释了为什么它适用于Git Bash.

要配置非标准命名 SSH 密钥,请执行以下步骤:

  1. 添加一个名为%HOMEPATH%\.ssh\config

  2. 编辑config类似以下内容(用于#添加评论):

    host github.com
     # My personal git repo for (something-cool)
     HostName github.com
     IdentityFile ~/.ssh/id_rsa_github
    
  3. 重启你的开发工具,比如Visual Studio Code


推荐阅读