Error: Permission denied (publickey)
这个郁闷的错误意味着服务器拒绝了您的连接。有许多原因会发生这种情况,本指南将介绍最常见的原因。
是否sudo
几乎所有情况下,你不应该使用 sudo
命令用git。如果你有原因需要要用,那么确保每一条指令都用(它可能只是用 su
获得root身份)。如果你生成SSH密钥没有 sudo
,那么当你试图使用 sudo git push
时,将不会使用你生成的SSH密钥。
确认连接正确的服务器
打字很不爽。要注意是不是打错了(笔者:唉~~),你将无法连接到“githib.com”或“guthub.com”。在某些情况下,可能是DNS解析或者被和谐了。请确保连接到正确地址或映射到正确的IP地址:
ssh -vT git@github.com # OpenSSH_5.6p1, OpenSSL 0.9.8r 8 Feb 2011 # debug1: Reading configuration data /Users/you/.ssh/config # debug1: Reading configuration data /etc/ssh_config # debug1: Applying options for * # debug1: Connecting to github.com [207.97.227.239] port 22.
连接地址应该是GitHub IP 地址, 端口 22, 除非你重新设置了 SSH over HTTPS.
使用 "git" 用户
所有连接都必须试用 "git"用户.如果试用别的,比如 "yourname@github.com" 肯定不行:
ssh -T billy.anyteen@github.com # Permission denied (publickey).
确保SSH使用了你的密钥
验证是否生成有密钥并在使用, 可以运行 ssh-add -l
:
ssh-add -l # 2048 a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/you/.ssh/id_rsa (RSA)
如果啥都显示,你需要给SSH添加你的你要,运行 ssh-add path/to/key
.
提示: 在大部分系统上 (~/.ssh/id_rsa
, ~/.ssh/id_dsa
和 ~/.ssh/identity
) 会自动被SSH加载. 如果生成密钥时没有改过文件名,那就不需要运行ssh-add path/to/key
.
获得更多信息
你可以通过尝试连接获得过多信息:
ssh -vT git@github.com # ... # debug1: identity file /Users/you/.ssh/id_rsa type -1 # debug1: identity file /Users/you/.ssh/id_rsa-cert type -1 # debug1: identity file /Users/you/.ssh/id_dsa type -1 # debug1: identity file /Users/you/.ssh/id_dsa-cert type -1 # ... # debug1: Authentications that can continue: publickey # debug1: Next authentication method: publickey # debug1: Trying private key: /Users/you/.ssh/id_rsa # debug1: Trying private key: /Users/you/.ssh/id_dsa # debug1: No more authentication methods to try. # Permission denied (publickey).
在例子里,我们没有用任何密钥。在 显示"identity file"行 结尾的“-1”代表,SSH不能找到文件。在下面"Trying private key" 行也表明没有找到文件。如果文件存在,应该分别显示“1” 和"Offering public key":
ssh -vT git@github.com # ... # debug1: identity file /Users/you/.ssh/id_rsa type 1 # ... # debug1: Authentications that can continue: publickey # debug1: Next authentication method: publickey # debug1: Offering RSA public key: /Users/you/.ssh/id_rsa
确保你的公钥在你的GitHub账号上登记
最后一点,GitHub需要知道你的公钥才能建立连接。你可以通过运行 ssh-add -l
和你账号登记的公钥进行对比确认:
ssh-add -l # 2048 a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/you/.ssh/id_rsa (RSA)
如果使用 ssh-add
不能连接到认证代理,代表你没有运行ssh-agent
。你可以通过以下命令打印你的 必要指纹:
ssh-keygen -lf ~/.ssh/id_rsa.pub
如果你有多个密钥,运行上面的命令时,最后的参数需要替换成你公钥文件的路径。