解决github 22端口被占用或封闭的问题
在使用 git push 或 Github Desktop 等其他 Git 操作时,可能遇到以下错误:
1 | ssh: connect to host github.com port 22: Connection timed out |
这是由于默认的 SSH 22 端口被防火墙或网络策略限制,导致无法连接到 GitHub 的服务器。
为了避免这一问题,可以将连接改为 SSH 的 443 端口。以下是详细的解决方法,包括 Windows 和 Linux/Mac 的操作步骤。
Linux/Mac 下操作步骤
- 修改 SSH 配置文件
SSH 的配置文件通常位于 ~/.ssh/config,如果文件不存在,可以手动创建一个:
1 | touch ~/.ssh/config |
打开文件并添加以下内容:
1 | Host github.com |
- 验证 SSH 配置
配置完成后,通过以下命令测试连接是否正常:
1 | ssh -T git@github.com |
如果配置成功,应该看到类似以下输出:
1 | Hi <your-username>! You've successfully authenticated, but GitHub does not provide shell access. |
- 配置 Git 使用新端口
为确保 Git 使用新的 443 端口,可以运行以下命令:
1 | git config --global url."ssh://git@ssh.github.com:443".insteadOf "ssh://git@github.com" |
Windows 下操作步骤
- 找到 SSH 配置文件
在 Windows 下,SSH 配置文件通常位于用户目录的 .ssh 文件夹中(例如:C:\Users<你的用户名>.ssh\config)。如果文件不存在,可以手动创建一个:
打开资源管理器并导航到 C:\Users<你的用户名>.ssh。
在 .ssh 文件夹下,新建一个文件,命名为 config(没有扩展名)。
2. 编辑 SSH 配置文件
用记事本或其他文本编辑器打开 config 文件,添加以下内容:
1 | Host github.com |
注意:
IdentityFile 的路径需要根据你实际存储 SSH 密钥的位置调整,通常是 id_rsa 或 id_ed25519。
- 验证 SSH 配置
打开命令提示符或 PowerShell,运行以下命令测试连接:
1 | ssh -T git@github.com |
如果配置正确,你应该看到以下输出:
1 | Hi <your-username>! You've successfully authenticated, but GitHub does not provide shell access. |
- 配置 Git 使用新端口
在命令提示符或 PowerShell 中运行以下命令:
最近这一步不配置,也可以正常使用 Github Desktop 了。
1 | git config --global url."ssh://git@ssh.github.com:443".insteadOf "ssh://git@github.com" |
总结
当 22 端口被占用或限制 时,通过将 SSH 连接切换到 443 端口,即可解决无法访问 GitHub 的问题。这种方法适用于任何操作系统,尤其是在防火墙限制较严的网络环境中。