Pyngrok不断取得联系

问题描述

我刚刚开始使用ngrok,并且在使用标准过程时,我可以使用./ngrok tcp 22启动隧道,并在我的仪表板中看到该隧道已打开,

但是我想使用pyngrok,并且在使用时在这里使用:

from pyngrok.conf import PyngrokConfig 
from pyngrok import ngrok

ngrok.set_auth_token("<NGROK_AUTH_TOKEN>")

pyngrok_config = PyngrokConfig(config_path="/opt/ngrok/ngrok.yml")

ngrok.get_tunnels(pyngrok_config=pyngrok_config) 
ssh_url  = ngrok.connect()

它连接并生成隧道,但是为什么仪表板上没有打开任何东西,为什么?

也许是因为python脚本执行并生成URL,然后停止并退出URL,但是随后如何使其继续运行,或者甚至如何使用python甚至API启动隧道?请使用python或API建议正确的脚本?

解决方法

Python进程终止后,带有ngrok隧道的线程将终止。因此,您是对的,发生这种情况的原因是您的脚本使用期限不长。完成此操作的最简单方法是by following the example in the documentation

另一个问题是如何设置authtoken。由于您未使用默认的config_path,因此需要在设置authtoken之前进行设置,以便在正确的文件中对其进行更新(还需要将其传递给connect() )。有几种方法可以执行此操作,但是最简单的方法from the docs是更新默认配置(因为如果不将pyngrok_config传递给以后的任何方法调用,则将使用此默认配置)

我还看到您的响应变量为ssh_url,因此您可能想启动到80(默认)— perhaps you've configured this in your ngrok.yml以外的端口的TCP隧道。否则,我已将调用更新为connect(),以确保这是为您启动的隧道类型,以防其他人尝试使用相同的代码段。

完全公开,我是pyngrok的开发人员。这是用我的更改更新的代码段。

import os,time

from pyngrok.conf import PyngrokConfig
from pyngrok import ngrok,conf

conf.get_default().config_path = "/opt/ngrok/ngrok.yml"

ngrok.set_auth_token(os.environ.get("NGROK_AUTH_TOKEN"))

ssh_tunnel = ngrok.connect(22,"tcp")

ngrok_process = ngrok.get_ngrok_process()

try:
    # Block until CTRL-C or some other terminating event
    ngrok_process.proc.wait()
except KeyboardInterrupt:
    print(" Shutting down server.")

    ngrok.kill()