【git】解决问题connect to host github.com port 22: Connection refused的方法
解决问题connect to host github.com port 22: Connection refused的方法
ssh: connect to host github.com port 22: Connection refused这个错误提示的是连接github.com的22端口被拒绝了。
网上搜索这个报错,发现很多人遇到这个问题,大概有2个原因和对应解决方案:
原因:这个问题其实就是DNS解析被污染了,有2种可能:
- DNS解析被运营商劫持了
- 使用了梯子
使用GitHub的443端口
端口 22 可能被防火墙屏蔽了,可以尝试连接GitHub的443端口:
$ vim ~/.ssh/config
# Add section below to it
Host github.com
Hostname ssh.github.com
Port 443
测试github连通性:
ssh -T git@github.com
输出:
Hi xxxxx! You've successfully authenticated, but GitHub does not
provide shell access.
如果~/.ssh目录下没有config文件,新建一个即可。修改完~/.ssh/config文件后,使用ssh -T git@github.com来测试和GitHub的网络通信是否正常,如果提示 Hi xxxxx! You've successfully authenticated, but GitHub does not provide shell access. 就表示一切正常了。
但是,这个方案在我这里行不通,修改后还是提示ssh: connect to host github.com port 443: Connection refused。这个方案有效的前提是:执行命令ssh -T -p 443 git@ssh.github.com后不再提示connection refused,所以要尝试这个方案的小伙伴先执行这条命令测试下。网上的招都没用,只能自力更生了。既然和GitHub建立ssh连接的时候提示connection refused,那我们就详细看看建立ssh连接的过程中发生了什么,可以使用ssh -v命令,-v表示verbose,会打出详细日志。
$ ssh -vT git@github.com
OpenSSH_9.0p1, OpenSSL 1.1.1o 3 May 2022
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to github.com [::1] port 22.
debug1: connect to address ::1 port 22: Connection refused
debug1: Connecting to github.com [127.0.0.1] port 22.
debug1: connect to address 127.0.0.1 port 22: Connection refused
ssh: connect to host github.com port 22: Connection refused
从上面的信息马上就发现了诡异的地方,连接github.com的地址居然是::1和127.0.0.1。前者是IPV6的localhost地址,后者是IPV4的localhost地址。
到这里问题就很明确了,是DNS解析出问题了,导致github.com域名被解析成了localhost的ip地址,就自然连不上GitHub了。
Windows下执行ipconfig /flushdns 清楚DNS缓存后也没用,最后修改hosts文件,增加一条github.com的域名映射搞定。
查找github.com的ip地址可以使用https://www.ipaddress.com/来查询,也可以使用nslookup命令
nslookup github.com 8.8.8.8
nslookup是域名解析工具,8.8.8.8是Google的DNS服务器地址。直接使用
nslookup github.com
就会使用本机已经设置好的DNS服务器进行域名解析,ipconfig /all可以查看本机DNS服务器地址。
参考资料
1. ssh: connect to host github.com port 22: Connection refused

浙公网安备 33010602011771号