A Python wrapper for ngrok that manages its own binary, making ngrok available via a convenient Python API
—
Core functionality for creating, listing, and managing ngrok tunnels including HTTP, TCP, and TLS tunnels with full configuration support and automatic binary management.
Establishes new ngrok tunnels with flexible configuration options supporting various protocols and tunnel definitions.
def connect(addr=None, proto=None, name=None, pyngrok_config=None, **options):
"""
Establish a new ngrok tunnel for the given protocol to the given port.
Parameters:
- addr (str, optional): Local port to forward traffic to, or local directory/network address. Defaults to "80"
- proto (str, optional): Tunnel protocol ("http", "tcp", "tls"). Defaults to "http"
- name (str, optional): Friendly name for the tunnel or name of tunnel definition in ngrok config
- pyngrok_config (PyngrokConfig, optional): Configuration override
- **options: Additional tunnel configuration options
Returns:
NgrokTunnel: The created tunnel object
Raises:
PyngrokError: When tunnel definition is invalid or response lacks public_url
"""Usage Examples:
from pyngrok import ngrok
# HTTP tunnel on default port 80
tunnel = ngrok.connect()
# HTTP tunnel on specific port
tunnel = ngrok.connect("8000")
# TCP tunnel for SSH
ssh_tunnel = ngrok.connect("22", "tcp")
# HTTP tunnel with custom domain (requires auth token)
tunnel = ngrok.connect("3000", subdomain="my-app")
# HTTPS-only tunnel
tunnel = ngrok.connect("8080", bind_tls=True)
# Named tunnel from config file
tunnel = ngrok.connect(name="my-tunnel-config")
# File serving
tunnel = ngrok.connect("file:///path/to/files", "http")Closes specific ngrok tunnels by their public URL.
def disconnect(public_url, pyngrok_config=None):
"""
Disconnect the ngrok tunnel for the given URL.
Parameters:
- public_url (str): The public URL of the tunnel to disconnect
- pyngrok_config (PyngrokConfig, optional): Configuration override
"""Usage Examples:
from pyngrok import ngrok
# Create and then disconnect a tunnel
tunnel = ngrok.connect("8000")
print(f"Tunnel created: {tunnel.public_url}")
# Disconnect by public URL
ngrok.disconnect(tunnel.public_url)Retrieves all currently active ngrok tunnels with their configuration and metrics.
def get_tunnels(pyngrok_config=None):
"""
Get a list of active ngrok tunnels.
Parameters:
- pyngrok_config (PyngrokConfig, optional): Configuration override
Returns:
list[NgrokTunnel]: List of active tunnel objects
Raises:
PyngrokError: When response is invalid or lacks public_url
"""Usage Examples:
from pyngrok import ngrok
# Create some tunnels
http_tunnel = ngrok.connect("8000")
tcp_tunnel = ngrok.connect("22", "tcp")
# List all active tunnels
tunnels = ngrok.get_tunnels()
for tunnel in tunnels:
print(f"Name: {tunnel.name}")
print(f"Public URL: {tunnel.public_url}")
print(f"Local Address: {tunnel.config['addr']}")
print(f"Protocol: {tunnel.proto}")
print("---")Terminates all ngrok processes and clears tunnel state.
def kill(pyngrok_config=None):
"""
Terminate all ngrok processes for the given config's ngrok_path.
Parameters:
- pyngrok_config (PyngrokConfig, optional): Configuration override
"""Usage Examples:
from pyngrok import ngrok
# Create some tunnels
ngrok.connect("8000")
ngrok.connect("9000")
# Terminate all ngrok processes and clear tunnels
ngrok.kill()
# Verify no tunnels remain
tunnels = ngrok.get_tunnels() # Will start new process
print(len(tunnels)) # Should be 0Each tunnel provides detailed information and metrics through the NgrokTunnel object.
class NgrokTunnel:
"""
Container for ngrok tunnel information and operations.
"""
id: str # Tunnel ID
name: str # Tunnel name
proto: str # Protocol (http, tcp, tls)
uri: str # API URI for tunnel operations
public_url: str # Public ngrok URL
config: dict # Tunnel configuration
metrics: dict # Traffic metrics
data: dict # Raw tunnel data from ngrok
pyngrok_config: PyngrokConfig # Configuration used
api_url: str # ngrok API URL
def refresh_metrics(self):
"""
Get the latest metrics for the tunnel and update the metrics variable.
Raises:
PyngrokError: When the API does not return metrics
"""Usage Examples:
from pyngrok import ngrok
# Create tunnel and inspect properties
tunnel = ngrok.connect("8000")
print(f"Tunnel ID: {tunnel.id}")
print(f"Name: {tunnel.name}")
print(f"Protocol: {tunnel.proto}")
print(f"Public URL: {tunnel.public_url}")
print(f"Local Address: {tunnel.config['addr']}")
# Access metrics
print(f"Requests Count: {tunnel.metrics.get('conns', {}).get('count', 0)}")
print(f"Bytes In: {tunnel.metrics.get('http', {}).get('bytes_in', 0)}")
# Refresh metrics to get latest data
tunnel.refresh_metrics()
print(f"Updated Requests: {tunnel.metrics.get('conns', {}).get('count', 0)}")Tunnels support extensive configuration through keyword arguments:
from pyngrok import ngrok
# HTTP tunnel with custom configuration
tunnel = ngrok.connect(
addr="8000",
proto="http",
subdomain="my-app", # Custom subdomain (requires auth)
hostname="example.com", # Custom hostname (requires auth)
auth="user:pass", # HTTP basic auth
bind_tls=True, # HTTPS only
inspect=False, # Disable request inspection
host_header="rewrite" # Host header handling
)
# TCP tunnel with configuration
tcp_tunnel = ngrok.connect(
addr="22",
proto="tcp",
remote_addr="1.tcp.ngrok.io:12345" # Fixed remote address
)Tunnel operations can raise various exceptions that should be handled appropriately:
from pyngrok import ngrok
from pyngrok.exception import PyngrokError, PyngrokNgrokError
try:
tunnel = ngrok.connect("8000", subdomain="taken-subdomain")
except PyngrokNgrokError as e:
print(f"ngrok error: {e}")
print(f"Error details: {e.ngrok_error}")
except PyngrokError as e:
print(f"pyngrok error: {e}")
try:
ngrok.disconnect("https://nonexistent.ngrok.io")
except Exception:
# Disconnect silently handles non-existent tunnels
passInstall with Tessl CLI
npx tessl i tessl/pypi-pyngrok