Search code examples
pythonremote-accessngrokpyngrok

Pyngrok to getting connecting continuously


I have just started using ngrok, and while using the standard procedure, I can start the tunnel using ./ngrok tcp 22 and see that tunnel open in my dashboard,

But I would like to use pyngrok, and here when I use:

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()

It connects and generates a tunnel, but I can't see anything open in the dashboard, why?

Maybe because the python script executes and generates URL and then stops and comes out of it, but then how to make it keep running, or how to even start a tunnel using python or even API ? Please suggest the correct script, using python or API?


Solution

  • The thread with the ngrok tunnel will terminate as soon as the Python process terminates. So you are correct, the reason this is happening is because your script is not long lived. The easiest way to accomplish this is by following the example in the documentation.

    Another issue is how you're setting the authtoken. Since you're not using the default config_path, you need to set this before setting the authtoken so it gets updated in the correct file (you'd also need to pass it to connect()). There are a couple ways to do this, but the easiest way from the docs is to just update the default config (since that's what will be used if you don't pass a pyngrok_config to any future method calls).

    I also see that you're response variable is ssh_url, so you probably want to start a TCP tunnel to a port other than 80 (the default)—perhaps you've configured this in your ngrok.yml, but if not, I've updated the call to connect() to ensure this is the type of tunnel started for you and in case others try to use this same code snippet.

    Full disclosure, I am the developer of pyngrok. Here is your code snippet updated with my changes.

    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()