pyngrok

8.0.0 · active · verified Sat Apr 11

pyngrok is a Python wrapper for ngrok, a reverse proxy tool that opens secure tunnels from public URLs to localhost. It manages its own ngrok binary, making the ngrok client available via a convenient Python API and the command line. This allows for rapid development, testing webhooks, and exposing local services. The current version is 8.0.0, and the library is actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize pyngrok, set an ngrok authtoken (preferably via an environment variable), and open a basic HTTP tunnel to a local port. It then prints the public ngrok URL and waits for user input before gracefully closing the tunnel. An ngrok authtoken is highly recommended for full functionality and can be obtained from the ngrok dashboard.

import os
from pyngrok import ngrok, conf

# Get your ngrok authtoken from the environment or replace with your actual token.
# You can obtain one from https://ngrok.com/signup
NGROK_AUTH_TOKEN = os.environ.get("NGROK_AUTHTOKEN", "YOUR_NGROK_AUTHTOKEN")

if NGROK_AUTH_TOKEN == "YOUR_NGROK_AUTHTOKEN":
    print("WARNING: Please set the NGROK_AUTHTOKEN environment variable or replace 'YOUR_NGROK_AUTHTOKEN' in the code.")
    print("         Some ngrok features may be limited without an authtoken.")
    # Attempt to set the authtoken anyway, it might work for basic free-tier tunnels
    conf.get_default().auth_token = NGROK_AUTH_TOKEN
else:
    ngrok.set_auth_token(NGROK_AUTH_TOKEN)

try:
    # Open an HTTP tunnel to a local service running on port 8000
    # Ensure a service is running on this port before connecting.
    http_tunnel = ngrok.connect(8000)
    print(f"ngrok tunnel is live: {http_tunnel.public_url}")

    # The tunnel will remain open until `ngrok.kill()` is called or the script exits.
    input("Press Enter to close the tunnel and exit...")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Disconnect any active ngrok tunnels and kill the ngrok process
    ngrok.kill()
    print("ngrok tunnel closed.")

view raw JSON →