如何排查SSH协议带密钥添加Git远程仓库的权限与连接问题?
Git远程仓库权限拒绝&连接超时问题排查与解决
问题描述
尝试为Git分支添加远程仓库地址,执行fetch或git ls-remote时出现权限拒绝错误:
myuser@22.22.22.222: Permission denied (publickey). fatal: Could not read from remote repository.
已在普通命令行和Git Bash中测试,均触发该错误。
对比验证:使用root用户以相同方式连接另一服务器的仓库可成功执行:
git remote add prod ssh://root@11.111.11.11:22/myfolder/gittest.git
成功输出:From ssh://root@22.222.22.22:22/myfolder/gittest.git
在问题服务器上,可通过指定密钥正常SSH登录:
ssh -i .ssh/mykey.pem myuser@22.22.22.222
但添加远程仓库时执行以下命令,无法自动使用指定的.pem密钥:
git remote add prod ssh://myuser@22.222.22.22:22/myfolder/gittest.git
初始配置与疑问
为让Git使用.pem密钥,在~/.ssh/config中添加如下配置:
Host theserver HostName 22.22.22.222 IdentityFile ~/.ssh/myfile.pem Port 22
存在疑问:如何验证.pem文件是否被Git读取?即使移除该config配置,也未出现“密钥缺失”类错误提示。
额外排查:确认服务器上仓库目录/myfolder/gittest.git存在,将仓库移至用户子目录后仍报错;查看服务器用户myuser的权限信息:
uid=1000(myuser) gid=1000(myuser) groups=1000(myuser),4(adm),20(dialout),24(cdrom), 25(floppy),27(sudo), 29(audio),30(dip),33(www-data),44(video),46(plugdev),119(netdev),120(lxd)
后续排查步骤
- 更新
~/.ssh/config配置,添加User和IdentitiesOnly字段,并修改远程仓库地址:
git remote add prod theserver:/myfolder/gittest.git
- 验证config文件读取情况:移除
~/.ssh/config后执行git ls-remote,提示Could not resolve hostname theserver,说明config存在时会被正常读取。 - 连接对比测试:在正常工作的服务器示例中,移除本地密钥后执行
git ls-remote,提示The authenticity of host '11.111.11.11' can't be established.,说明能建立连接但认证失败;但问题服务器上执行git ls-remote仅返回:
ssh: connect to host 22.22.22.222 port 22: Connection timed out fatal: Could not read from remote repository.
即使将config中的IP改为错误地址,报错信息仍一致,看似与密钥无关,但普通SSH可正常访问该服务器。
最终解决方法
该异常由VPN连接导致:目标服务器需要通过VPN访问,开启VPN后,使用git remote add prod theserver:/myfolder/gittest.git即可正常连接远程仓库。
内容的提问来源于stack exchange,提问作者Galivan
相关产品推荐
相关产品推荐

