S
sharpmind.tech
Git
创建时间:

解决 git push 出现 port 22: Connection timed out

解决 git push 出现 port 22: Connection timed out - 详细内容介绍

问题背景

在日常使用 GitHub 的时候,有时会遇到这样的报错:

ssh: connect to host github.com port 22: Operation timed out
fatal: Could not read from remote repository.

我在测试时发现两种情况:

  • 关闭代理时

    git clone git@github.com:kxzb-fun/ks.git
    ssh: connect to host github.com port 22: Operation timed out

    → 直连 github.com:22 超时。

  • 打开代理时

    git clone git@github.com:kxzb-fun/ks.git
    Connection closed by 127.0.0.1 port 7890

    → 说明流量被代理劫持到了本地端口 127.0.0.1:7890,但代理并没有正确处理 SSH,连接被直接关闭。

结论: 22 端口被网络环境屏蔽,而代理又不支持 SSH 转发,导致 push/pull 都失败。

解决方案:使用 SSH 的 443 端口

GitHub 默认用 22 端口提供 SSH 服务,但也贴心地在 ssh.github.com:443 提供了备用通道,专门为 22 被封的情况准备。

  1. 编辑 SSH 配置:

    vim ~/.ssh/config

    添加以下内容:

    Host github.com
      HostName ssh.github.com
      Port 443
      User git
      IdentityFile ~/.ssh/id_ed25519   # 或 ~/.ssh/id_rsa,按实际私钥
      IdentitiesOnly yes
      ServerAliveInterval 60
  2. 测试连通:

    ssh -T git@github.com

    如果返回:

    Hi <username>! You've successfully authenticated, but GitHub does not provide shell access.

    就说明 SSH 已经能正常连通。

  3. 之后正常使用:

    git push
    git pull
    git clone git@github.com:<username>/<repo>.git

22 端口和 443 端口的区别

  • 22 端口

    • 默认用于 SSH 协议
    • GitHub 的 git@github.com:xxx/xxx.git 默认就是走 22。
  • 443 端口

    • 默认用于 HTTPS 协议(SSL/TLS 加密)
    • 但 GitHub 在 ssh.github.com:443额外挂载了 SSH 服务,让 SSH 可以“伪装”成走 443,从而绕过防火墙限制。

所以,当你在 ~/.ssh/config 里改成 443 时,走的依然是 SSH 协议,只是端口换成了 443。


为什么 22 容易被屏蔽?

  • 安全管控:公司、学校、公共 Wi-Fi 常常屏蔽 22,防止用户绕过内网直接 SSH 出去。
  • 翻墙限制:有些地区的网络会专门封 22,因为很多代理/隧道工具喜欢伪装成 SSH。
  • 运营商策略:部分 ISP 屏蔽家庭宽带的 22,避免用户自己搭建服务器。
  • 公共网络策略:咖啡厅、机场的 Wi-Fi 通常只开放 80 和 443,其他端口一律禁止。

而 443 端口几乎不会被封,因为它是网页加密访问的必需端口。


总结

  1. ssh: connect to host github.com port 22: Connection timed out 的核心原因是 22 端口被屏蔽
  2. 代理(127.0.0.1:7890)如果不支持 SSH,就会导致 Connection closed
  3. 最佳解决方案:修改 ~/.ssh/config,改用 SSH over 443
  4. 443 是 HTTPS 默认端口,但 GitHub 特意在 443 上也提供了 SSH 服务,用来绕过限制。

这样就能在任何网络环境下顺利 git push / pull / clone 了 🚀