问题现象

​ 本文以 Windows 系统为例进行说明。

​ 在更换网络环境后,在个人电脑上使用 git push 命令推动代码至 Github 报错。

ssh: connect to host github.com port 22: Connection refused
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

排查过程

​ 报错提示的是连接 github.com 的 22 端口被拒绝了。遂使用浏览器访问 github.com,确实无法访问,开梯子后网页访问正常,但 git push 依旧失败。

使用 Github 的 443 端口

​ 网上搜索后发现可能是 22 端口被防火墙屏蔽了,可以尝试连接 Github 的 443 端口。

​ 命令 ssh -T git@github.com 可以检测和 Github 的网络通信是否正常,执行后报错 连接超时

​ 接着执行命令 ssh -T -p 443 git@ssh.github.com 测试 443 端口能否通信,提示 “Hi xxxxx! You’ve successfully authenticated, but GitHub does notprovide shell access”,则表示连接正常。

​ 那就可以在 ~/.ssh/config 文件中配置以下内容,这样 ssh 在连接 Github 的时候就会使用 443 端口。如果~/.ssh目录下没有 config 文件,新建一个即可。(如果新建 config 后执行 git 操作报错 Bad owner or permissions on xxx/.ssh/config,可见下文解决思路)

Host github.com
  Hostname ssh.github.com
  Port 443

​ 至此完成以上操作后 git 的 ssh 连接恢复正常。另外网络上还有其他解决方案,没有尝试过但先列举在这里,以后说不定会用上。

将使用 ssh 协议更改为 https 协议

在 GitHub 的本地 repo 目录,执行如下命令:

$ git config --local -e

然后把里面的 url 配置项从 git 格式

url = git@github.com:username/repo.git

修改为 https 格式

url = https://github.com/username/repo.git

这个其实修改的是 repo 根目录下的.git/config文件。

新建 .ssh/config 文件执行 git 操作报错 Bad owner or permissions on xxx/.ssh/config

​ 这个错误的原因是:文件夹.ssh 的权限不仅仅是 windows 当前用户拥有或者当前用户权限不足,故修改权限即可。

解决方法:

  1. 找到 .ssh 文件夹,它通常位于 C:\Users。
  2. 右键单击 .ssh 文件夹,单击“属性”,再点击安全标签。
  3. 单击 高级 > 禁用继承,单击确定。 会出现警告弹出窗口,点击从此对象中删除所有继承的权限
  4. 你能看到所有用户都将被删除。让我们添加所有者。在同一窗口中,单击编辑按钮。
  5. 单击添加以显示选择用户或组窗口。
  6. 单击高级,然后单击“立即查找”按钮。应显示用户结果列表。 选择您的用户帐户。
  7. 然后单击确定(大约三次)以关闭所有窗口。
  8. 完成所有操作后, 尝试连接到远程 SSH 主机,这个问题应该解决了。