Mac ssh Permission denied (publickey). fatal: Could not read from remote repository.

新手Mac开发环境配置,sourcetree和bitbucket经历重重问题终于配好了连上了,但是关机重启后发现pull和push操作又不管用了,报错:

[email protected]: Permission denied (publickey). fatal: Could not read from remote repository.

Mac ssh Permission denied (publickey). fatal: Could not read from remote repository.

检查.ssh/目录下的公钥私钥文件都存在,并且config文件中的配置都没问题,IdentityFile指向对应连接bitbucket的pub文件。

我本地两个ssh,一个连git,一个连bitbucket

Mac ssh Permission denied (publickey). fatal: Could not read from remote repository.
Mac ssh Permission denied (publickey). fatal: Could not read from remote repository.

命令行输入cat ~/.ssh/你的公钥.pub查看本地xxx.pub文件和bitbucket上配置的ssh,也是一样的(此处不想对比可以重新配置一下远程的ssh)。
用ssh -v去连有问题的服务器,会有比较详细的调试信息在屏幕上输出,可以帮助判断是哪一步出了问题。主要是看是客户端还是服务器的问题,如果是客户端的问题,应该log中有写。如果是没有什么有用信息,就可能是服务器端出问题了。
输入ssh -v [email protected]查看错误信息如下:
Mac ssh Permission denied (publickey). fatal: Could not read from remote repository.

然后输入ssh-add -l查看agent中是否有ssh key,果然没有。。。
Mac ssh Permission denied (publickey). fatal: Could not read from remote repository.

至此找到问题所在,引起错误原因是没有添加ssh key到authentication agent中。在Mac中,每次关机重启agent配置都会失效,因为是临时的存储。ssh-add命令是把专用**添加到ssh-agent的高速缓存中。

命令行输入ssh-add ~/.ssh/你的私钥文件,输入密码,将ssh key添加到agent高速缓存中就可以了,查看agent列表生成成功,测试链接成功。

Mac ssh Permission denied (publickey). fatal: Could not read from remote repository.
Mac ssh Permission denied (publickey). fatal: Could not read from remote repository.

总结:如果本地ssh和远程ssh配置都没有问题,查看agent高速缓存列表,一般重启就会导致配置失败需要重新添加到缓存,网上查可以在ssh-add -K添加成永久的,目前还没关过机测试,回头试了再来改博客。

这个问题的回答很系统的解释了ssh及add相关内容:https://segmentfault.com/q/1010000000835302