git push 出现 ssh: connect to host github.com port 22: Connection timed out
错误的原因及解决方案
在使用 Git 推送代码到 GitHub 时,有时会遇到如下错误:
ssh: connect to host github.com port 22: Connection timed out
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
本文将总结这一错误出现的常见原因及相应的解决方案。
常见原因分析
- 网络问题:
- 网络连接不稳定或网络提供商限制了对外部服务器的 SSH 端口(通常是 22)的访问。
- 防火墙和安全设置:
- 公司、学校或其他组织的网络防火墙可能会阻止 SSH 连接到 GitHub 的默认端口(22)。
- GitHub 服务器访问限制:
- 虽然这种情况较少见,但 GitHub 服务器可能临时关闭或访问受到限制。
- SSH 配置问题:
- 本地 SSH 配置文件中未正确配置连接选项,或 SSH 密钥未正确添加到 GitHub。
解决方案
1. 检查网络连接
- 切换网络:尝试使用不同的网络,例如移动热点,来排除本地网络问题。
- Ping 测试:使用
ping github.com
命令测试网络连通性。
2. 更改 SSH 连接端口
-
使用端口 443 替代端口 22:
如果你的网络防火墙阻止了 SSH 端口 22,可以通过将连接端口更改为 443 来绕过限制。步骤:
- 编辑或创建
~/.ssh/config
文件:nano ~/.ssh/config
- 添加以下内容:
Host github.com Hostname ssh.github.com Port 443
- 保存并退出文件。
- 编辑或创建
3. 验证 SSH 配置
- 使用以下命令验证 SSH 是否能正确连接到 GitHub:
如果看到类似ssh -T git@github.com
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
的提示,说明 SSH 配置正常。
4. 检查 SSH 密钥
- 生成新密钥(如有必要):
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
- 添加公钥到 GitHub:
- 复制公钥内容:
cat ~/.ssh/id_rsa.pub
- 登录 GitHub,进入
Settings > SSH and GPG keys
,点击 New SSH Key,粘贴公钥并保存。
- 复制公钥内容:
5. 使用 HTTPS 替代 SSH(临时解决方案)
- 如果无法解决 SSH 连接问题,可以暂时使用 HTTPS:
推送或拉取时将需要使用 GitHub 个人访问令牌来代替密码。git remote set-url origin https://github.com/your-username/your-repo.git
总结
git push
出现 ssh: connect to host github.com port 22: Connection timed out
错误时,最常见的原因是网络限制或 SSH 配置问题。通过更改连接端口、验证 SSH 配置或使用 HTTPS,可以有效地解决此类问题。希望这些方法能帮助你顺利推送代码到 GitHub。