Permission denied when pushing to Github

现象

添加 remote 后,通过 git 协议 push 代码

1
2
$ git remote add origin git@github.com:angryz/icloudaegis_ejbca.git
$ git push -u origin master

此时出现错误提示

1
2
3
4
5
6
Warning: Permanently added the RSA host key for IP address '192.30.252.131' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

处理

调试 ssh 连接

1
$ ssh -vT git@github.com

查看结果,连接正常,仍然报错 Permission denied (publickey).

检查 ssh 校验key是否是正常的

1
2
$ ssh-add -l
The agent has no identities.

没有打印出 key 信息,说明 ssh 连接时没有正确使用 key。

查看自己的 key 文件

1
$ ls ~/.ssh

在该目录下发现 github_rsa,接下来将其添加到 ssh

1
$ ssh-add ~/.ssh/github_rsa

然后再运行 ssh -vT git@github.com,正常。

总结

通常系统使用 ssh 协议时默认使用的 key 文件是 ~/.ssh/id_rsa,如果你针对某些 ssh 连接的 key 文件没有覆盖系统默认的 id_rsa,而是保存为自定义的文件名,那么就需要手动通过 ssh-add 将其添加到 ssh 协议的查找对象中。

参考 Github help: Error: Permission denied (publickey)