You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ngrok建立Google Colab SSH隧道时遭遇ConnectionRefusedError

解决Colab通过Ngrok建立SSH隧道的ConnectionRefusedError问题

问题概述

尝试使用Ngrok为Google Colab实例建立SSH隧道时,出现ConnectionRefusedError,提示无法建立连接,可能原因包括Ngrok配置错误、防火墙限制、端口转发不正确、Colab实例问题或Ngrok免费版限制等。

报错详情

ConnectionRefusedError                    Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/urllib3/connection.py in _new_conn(self)
    202         try:
--> 203             sock = connection.create_connection(
    204                 (self._dns_host, self.port),

18 frames
ConnectionRefusedError: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

NewConnectionError                        Traceback (most recent call last)
NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7cda712b1f90>: Failed to establish a new connection: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

MaxRetryError                             Traceback (most recent call last)
MaxRetryError: HTTPConnectionPool(host='localhost', port=4040): Max retries exceeded with url: /api/tunnels (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7cda712b1f90>: Failed to establish a new connection: [Errno 111] Connection refused'))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    517                 raise SSLError(e, request=request)
    518 
--> 519             raise ConnectionError(e, request=request)
    520 
    521         except ClosedPoolError as e:

ConnectionError: HTTPConnectionPool(host='localhost', port=4040): Max retries exceeded with url: /api/tunnels (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7cda712b1f90>: Failed to establish a new connection: [Errno 111] Connection refused'))

执行的操作步骤

# Install useful stuff
!apt-get update > /dev/null
!apt-get install --yes ssh screen nano htop ranger git > /dev/null

# SSH setting
!echo "root:hello" | chpasswd
!echo "PasswordAuthentication yes" > /etc/ssh/sshd_config
!echo "PermitUserEnvironment yes" >> /etc/ssh/sshd_config
!echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
!service ssh restart > /dev/null

# Download ngrok
!wget -q -c -nc https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip -qq -n ngrok-stable-linux-amd64.zip

# Run ngrok
authtoken = "2LSXUPuvhq7GioEKGLXOsTX4tUT_RX5wTzEfvKUTwZAkHfyo"
get_ipython().system_raw('./ngrok authtoken $authtoken -region ap && ./ngrok tcp 22 &')
!sleep 3

# Get the address for SSH
import requests
from re import sub
r = requests.get('http://localhost:4040/api/tunnels')
str_ssh = r.json()['tunnels'][0]['public_url']
str_ssh = sub("tcp://", "", str_ssh)
str_ssh = sub(":", " -p ", str_ssh)
str_ssh = "ssh root@" + str_ssh
print(str_ssh)

排查与解决方法

  • 验证Ngrok认证令牌:确认authtoken正确,无过期或输入错误,替换为从Ngrok控制台获取的有效令牌后重新运行脚本。
  • 确认Ngrok进程状态:运行!ps aux | grep ngrok检查Ngrok是否启动。若未启动,拆分Ngrok命令分步执行,避免前序命令失败导致后续不执行:
    !./ngrok authtoken $authtoken -region ap
    !./ngrok tcp 22 &
    
  • 延长启动等待时间:将!sleep 3改为!sleep 5或!sleep 10,确保Ngrok的API服务(4040端口)完全启动后再请求隧道信息。
  • 检查SSH服务状态:执行!service ssh status确认SSH服务正常运行,若未启动重新执行!service ssh restart,同时检查sshd_config配置项是否生效。
  • 确保Colab实例活跃:Colab免费实例可能因闲置被回收,重启Colab运行时后重新执行脚本,确保实例处于活跃状态。
  • 检查端口占用:执行!lsof -i :4040查看4040端口是否被占用,若有占用可杀掉对应进程,或通过--api-port指定其他端口:
    !./ngrok tcp 22 --api-port 4041 &
    
    同时将请求URL改为http://localhost:4041/api/tunnels。
  • 检查Ngrok免费版限制:免费版Ngrok有并发连接和隧道数量限制,若超出限制等待一段时间后重试,或考虑升级付费版。

内容的提问来源于stack exchange,提问作者Jhngir Khn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:02:13