问题
在使用 ssh-keygen 创建 github 秘钥时没有使用默认文件,而是自定义了 xxx.github 的秘钥文件,然后将公钥添加到 github 上。之后发现每次 Mac 开机后使用 git pull 拉取代码时都会提示 Permission denied (publickey) 的问题,如下:
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
我的 Mac 电脑型号:macOS 13.2.1 。
问题的原因是没有将私钥添加到 Keychain 中,需要使用 ssh-add 命令将私钥添加到 Keychain 中。
解决方法有两种,一种是临时方法,一种是永久方法。
注意,该方法仅对 Mac 电脑有效。
方法1:临时方法
在命令行执行如下命令:
ssh-agent -s
ssh-add ~/.ssh/id_ed25519.github
注意,id_ed25519.github 替换成你自己的私钥文件名(不带 .pub 后缀的文件)。
但是这种方法只在本次开机有效,下次开机时,仍需再执行一次,推荐使用下面的永久方法。
方法2:永久方法 (推荐)
参考:How can I permanently add my SSH private key to Keychain so it is automatically available to ssh?
按照如下步骤设置,该方法永久有效,即使在电脑重新开机时也会有效。
解决方法:
- 第一步:命令行执行 ssh-add
ssh-add --apple-use-keychain ~/.ssh/id_ed25519.github
- 第二步:在
~/.ssh/config中添加如下内容(文件若不存在则创建):
Host github.com
UseKeychain yes
AddKeysToAgent yes
IdentityFile ~/.ssh/id_ed25519.github
注意,id_ed25519.github 替换成你自己的私钥文件名(不带 .pub 后缀的文件)。
然后就可以使用 git pull 拉代码啦。

当在Mac上使用非默认ssh-keygen创建的GitHub密钥文件时,可能会遇到Git拉取代码失败的问题。原因在于私钥未添加到Keychain。解决方案包括临时方法(通过ssh-agent和ssh-add命令添加私钥)和永久方法(修改ssh配置文件并启用Keychain集成)。永久方法涉及在~/.ssh/config中添加特定配置,并使用ssh-add--apple-use-keychain命令。
780

被折叠的 条评论
为什么被折叠?



