pyngrok
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
- breaking pyngrok version compatibility with ngrok binary. pyngrok 8.x aims to work with ngrok v3. If you have an older or conflicting ngrok binary on your system path, or if an older pyngrok (e.g., v7.x) installed ngrok v2, you might experience unexpected behavior or errors when trying to use v3-specific features.
- gotcha Ngrok Authtoken is crucial for advanced features. Without an authenticated ngrok agent, features like custom subdomains, reserved addresses, or increased tunnel durations are unavailable. Failing to set the `NGROK_AUTHTOKEN` can lead to `ngrok` launching with limitations.
- gotcha PyngrokNgrokError on process startup. This error (e.g., 'The ngrok process was unable to start') often indicates an issue with the underlying ngrok binary's configuration or environment, not necessarily a bug in pyngrok.
- gotcha Tunnel connection refusal if no local service is running. If `ngrok.connect()` reports 'Failed to complete tunnel connection' or 'dial tcp 127.0.0.1:80: connect: connection refused', it means no service is actively listening on the target `localhost:port` specified.
Install
-
pip install pyngrok
Imports
- ngrok
from pyngrok import ngrok
- conf
from pyngrok import conf
Quickstart
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.")