### Run ngrok from the command line Source: https://github.com/alexdlaird/pyngrok/blob/develop/README.md Example of using the ngrok command-line interface to expose a local HTTP server running on port 80. This leverages the ngrok binary installed by pyngrok. ```sh ngrok http 80 ``` -------------------------------- ### Install pyngrok with pip Source: https://github.com/alexdlaird/pyngrok/blob/develop/README.md Install pyngrok using pip. This is the standard method for installing Python packages. ```sh pip install pyngrok ``` -------------------------------- ### v3 Ngrok Configuration File Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Example of a v3 ngrok configuration file defining endpoints. ```yaml version: "3" endpoints: - name: my-config-file-tunnel upstream: url: http://localhost:8000 protocol: http1 pooling_enabled: true - name: pyngrok-default upstream: url: http://localhost:80 ``` -------------------------------- ### Docker Compose with pyngrok Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Example docker-compose.yml to run the pyngrok container, execute a Python script, and expose the web inspector. ```yaml services: ngrok: image: alexdlaird/pyngrok env_file: ".env" command: - "python /root/my-script.py" volumes: - ./my-script.py:/root/my-script.py ports: - 4040:4040 ``` -------------------------------- ### Launch pyngrok Docker Container Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Run the pre-built pyngrok Docker image to get an interactive Python shell. ```shell docker run \ -e NGROK_AUTHTOKEN=$NGROK_AUTHTOKEN -it alexdlaird/pyngrok ``` -------------------------------- ### Start ngrok Headless Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/troubleshooting.rst Test starting ngrok without any tunnels to ensure the core process can launch. This helps isolate issues to tunnel configuration rather than ngrok itself. ```shell ngrok start --none --log stdout ``` -------------------------------- ### Install pyngrok in Google Colab Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Install the pyngrok library as a dependency within a Google Colaboratory notebook. ```sh !pip install pyngrok ``` -------------------------------- ### TCP Client Socket Creation Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst This Python snippet shows the initial setup for a TCP client, including creating a socket and retrieving host and port from environment variables. ```python import os import socket host = os.environ.get("HOST") port = int(os.environ.get("PORT")) # Create a TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ``` -------------------------------- ### Run FastAPI with ngrok Tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Start your Uvicorn server with the USE_NGROK environment variable set to True to enable the ngrok tunnel. ```sh USE_NGROK=True NGROK_AUTHTOKEN=$NGROK_AUTHTOKEN \ uvicorn server:app ``` -------------------------------- ### Start a Simple HTTP Tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/troubleshooting.rst Attempt to start a basic HTTP tunnel to port 80. This verifies ngrok's ability to create and manage tunnels, outputting logs to stdout for debugging. ```shell ngrok http 80 --log stdout ``` -------------------------------- ### Run Flask Development Server with ngrok Tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Command to start the Flask development server with ngrok enabled. Ensure NGROK_AUTHTOKEN is set for authentication. ```sh USE_NGROK=True NGROK_AUTHTOKEN=$NGROK_AUTHTOKEN \ FLASK_APP=server.py \ flask run ``` -------------------------------- ### Run Django Development Server with ngrok Tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Command to start the Django development server with ngrok enabled. Ensure NGROK_AUTHTOKEN is set for authentication. ```sh USE_NGROK=True NGROK_AUTHTOKEN=$NGROK_AUTHTOKEN \ python manage.py runserver ``` -------------------------------- ### Launch pyngrok Docker Container in Bash Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Start the pyngrok Docker container and access a bash shell instead of the default Python shell. ```shell docker run \ -e NGROK_AUTHTOKEN=$NGROK_AUTHTOKEN -it alexdlaird/pyngrok \ /bin/bash ``` -------------------------------- ### Run TCP Server with ngrok and Environment Variables Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst This shell command starts the TCP server script, setting the NGROK_AUTHTOKEN, HOST, and PORT environment variables required for the ngrok tunnel. ```sh NGROK_AUTHTOKEN=$NGROK_AUTHTOKEN \ HOST="1.tcp.ngrok.io" PORT=12345 \ python server.py ``` -------------------------------- ### Install pyngrok with conda Source: https://github.com/alexdlaird/pyngrok/blob/develop/README.md Install pyngrok using conda. This is an alternative installation method for users of the Anaconda distribution. ```sh conda install -c conda-forge pyngrok ``` -------------------------------- ### Expose HTTP Server with pyngrok Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Exposes a local HTTP server running on a specified port to the internet via an ngrok tunnel. Assumes Flask is installed. ```python import os import threading from flask import Flask from pyngrok import ngrok app = Flask(__name__) port = "5000" # Open a ngrok tunnel to the HTTP server public_url = ngrok.connect(port).public_url print(f" * ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\"") # Update any base URLs to use the public ngrok URL app.config["BASE_URL"] = public_url # ... Implement updates necessary so webhooks use `public_url` from ngrok # Define Flask routes @app.route("/") def index(): return "Hello from Colab!" # Start the Flask server in a new thread threading.Thread(target=app.run, kwargs={"use_reloader": False}).start() ``` -------------------------------- ### Initialize pyngrok Tunnel in Django AppConfig Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Integrate pyngrok initialization into Django's AppConfig.ready() method to automatically create an ngrok tunnel when the development server starts. ```python import os import sys from urllib.parse import urlparse from django.apps import AppConfig from django.conf import settings class CommonConfig(AppConfig): name = "myproject.common" verbose_name = "Common" def ready(self): if settings.USE_NGROK: # Only import pyngrok and install if we're actually going to use it from pyngrok import ngrok # Get the dev server port (defaults to 8000 for Django, can be overridden with the # last arg when calling `runserver`) addrport = urlparse(f"http://{sys.argv[-1]}") port = addrport.port if addrport.netloc and addrport.port else "8000" # Open a ngrok tunnel to the dev server public_url = ngrok.connect(port).public_url print(f"ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\"") # Update any base URLs or webhooks to use the public ngrok URL settings.BASE_URL = public_url CommonConfig.init_webhooks(public_url) @staticmethod def init_webhooks(base_url): # ... Implement updates necessary so webhooks use `public_url` from ngrok pass ``` -------------------------------- ### Set ngrok Binary Path with PyngrokConfig Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Use your own ngrok binary by specifying its path using PyngrokConfig. This is useful if you have a specific ngrok version or installation you wish to use. ```python from pyngrok import conf, ngrok conf.get_default().ngrok_path = "/usr/local/bin/ngrok" # .ngrok.io" -> "http://localhost:80"> ngrok_tunnel = ngrok.connect() ``` -------------------------------- ### Check ngrok Command Line Availability Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/troubleshooting.rst Verify that ngrok is accessible from your command line and that pyngrok's version is recognized. This ensures ngrok is correctly installed and in your system's PATH. ```shell ngrok ngrok - tunnel local ports to public URLs and inspect traffic USAGE: ngrok [command] [flags] ... PYNGROK VERSION: |pyngrok_version| ``` -------------------------------- ### Get active tunnels Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Retrieves a list of all currently active ngrok tunnels. ```python from pyngrok import ngrok # [.ngrok.io" -> "http://localhost:80">] tunnels = ngrok.get_tunnels() ``` -------------------------------- ### Expose Python HTTP Server with pyngrok Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst This Python script uses pyngrok to expose a local HTTP server to the web. It starts a basic HTTP server and creates a public ngrok tunnel to it. ```python import os from http.server import HTTPServer, BaseHTTPRequestHandler from pyngrok import ngrok port = os.environ.get("PORT", "80") server_address = ("", port) httpd = HTTPServer(server_address, BaseHTTPRequestHandler) public_url = ngrok.connect(port).public_url print(f"ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\"") try: # Block until CTRL-C or some other terminating event httpd.serve_forever() except KeyboardInterrupt: print(" Shutting down server.") httpd.socket.close() ``` -------------------------------- ### Get and Wait for Ngrok Process Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Obtain the ngrok process and block until it terminates (e.g., via KeyboardInterrupt). This is useful for short-lived applications like CLIs. ```python from pyngrok import ngrok 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() ``` -------------------------------- ### Get Active Tunnels Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Retrieve a list of all currently active tunnels managed by pyngrok using the `ngrok.get_tunnels()` method. ```APIDOC ## Get Active Tunnels It can be useful to ask the ``ngrok`` client what tunnels are currently open. This can be accomplished with the :func:`~pyngrok.ngrok.get_tunnels` method, which returns a list of :class:`~pyngrok.ngrok.NgrokTunnel` objects. ### Method `pyngrok.ngrok.get_tunnels()` ### Response - Returns: list[:class:`~pyngrok.ngrok.NgrokTunnel`] - A list of all currently active ngrok tunnels. ``` -------------------------------- ### Override Auth Token and API Key with PyngrokConfig Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Override the installed auth token or API key using PyngrokConfig. This allows for dynamic configuration without modifying global settings. ```python from pyngrok import conf, ngrok conf.get_default().auth_token = "" conf.get_default().api_key = "" # .ngrok.io" -> "http://localhost:80"> ngrok_tunnel = ngrok.connect() ``` -------------------------------- ### Configure Logging and Connect to ngrok Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/troubleshooting.rst This snippet demonstrates how to configure Python's logging to capture detailed debug information from pyngrok and then establish a connection. It's useful for diagnosing connection issues. ```python import logging from pyngrok import ngrok logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")) logger.addHandler(handler) ngrok.connect() ``` -------------------------------- ### Run Python HTTP Server with ngrok Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst This shell command demonstrates how to run the Python HTTP server script while setting the NGROK_AUTHTOKEN environment variable. ```sh NGROK_AUTHTOKEN=$NGROK_AUTHTOKEN python server.py ``` -------------------------------- ### Open an internal endpoint with load balancing Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Opens an internal endpoint with a specified domain and enables load balancing. ```python from pyngrok import ngrok # Open an Internal Endpoint that's load balanced # "http://localhost:9000"> internal_endpoint = ngrok.connect(addr="9000", domain="some-endpoint.internal", pooling_enabled=True) ``` -------------------------------- ### pyngrok Integration with unittest.TestCase Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Extends unittest.TestCase to manage a development server and an ngrok tunnel for end-to-end testing. Includes fixtures for starting/stopping the server and tunnel. ```python import os import signal import unittest import threading from flask import request from pyngrok import ngrok from urllib import request from server import create_app class PyngrokTestCase(unittest.TestCase): @classmethod def start_dev_server(cls): app = create_app() def shutdown(): # Newer versions of Werkzeug and Flask don't provide this environment variable if "werkzeug.server.shutdown" in request.environ: request.environ.get("werkzeug.server.shutdown")() else: # Windows does not provide SIGKILL, go with SIGTERM then sig = getattr(signal, "SIGKILL", signal.SIGTERM) os.kill(os.getpid(), sig) @app.route("/shutdown", methods=["POST"]) def route_shutdown(): shutdown() return "", 204 threading.Thread(target=app.run).start() return app @classmethod def stop_dev_server(cls): req = request.Request("http://localhost:5000/shutdown", method="POST") request.urlopen(req) @classmethod def setUpClass(cls): # Ensure a tunnel is opened and webhooks initialized when the dev server is started os.environ["USE_NGROK"] = "True" app = cls.start_dev_server() cls.base_url = app.config["BASE_URL"] # ... Implement other initializations that your tests need for assertions @classmethod def tearDownClass(cls): cls.stop_dev_server() ngrok.kill() ``` -------------------------------- ### Open HTTP, SSH, and named tunnels Source: https://github.com/alexdlaird/pyngrok/blob/develop/README.md Demonstrates opening different types of tunnels using the ngrok.connect() method. This includes default HTTP, TCP for SSH, and tunnels defined in a configuration file. ```python from pyngrok import ngrok # Open a HTTP tunnel on the default port 80 # .ngrok.io" -> "http://localhost:80"> http_tunnel = ngrok.connect() # Open a SSH tunnel # "localhost:22"> ssh_tunnel = ngrok.connect("22", "tcp") # Open a named tunnel from the config file named_tunnel = ngrok.connect(name="my-config-file-tunnel") # Open an Internal Endpoint that's load balanced # "http://localhost:9000"> internal_endpoint = ngrok.connect(addr="9000", domain="some-endpoint.internal", pooling_enabled=True) ``` -------------------------------- ### Run Client with ngrok Tunnel Environment Variables Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst This shell command shows how to run a Python client script that connects to an ngrok tunnel. It sets the HOST and PORT environment variables required by the client to establish the connection. ```sh HOST="1.tcp.ngrok.io" PORT=12345 \ python client.py ``` -------------------------------- ### Configure ngrok Tunnel in Django Settings Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Set up Django settings to enable ngrok tunneling for local development. This involves defining USE_NGROK and BASE_URL based on environment variables. ```python import os import sys # ... Implement the rest of your Django settings BASE_URL = "http://localhost:8000" USE_NGROK = os.environ.get("USE_NGROK", "False") == "True" and os.environ.get("RUN_MAIN", None) != "true" ``` -------------------------------- ### Configure Tunnel with Authentication and Subdomain Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Opens a tunnel with a specific subdomain, basic authentication, and a circuit breaker configuration. ```python from pyngrok import conf, ngrok # "http://localhost:80"> ngrok_tunnel = ngrok.connect(subdomain="foo", auth="username:password", circuit_breaker=50) ``` -------------------------------- ### Mount Custom ngrok Config in Docker Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Provide a custom ngrok configuration file to the pyngrok Docker container by mounting your local ngrok.yml. ```shell docker run \ -v ./ngrok.yml:/root/.config/ngrok/ngrok.yml -it alexdlaird/pyngrok ``` -------------------------------- ### Reserve Domain and Create Cloud Endpoint via API Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Uses the ngrok API to reserve a domain and create a Cloud Endpoint with a traffic policy. ```python from pyngrok import ngrok domain = "some-domain.ngrok.dev" ngrok.api("reserved-domains", "create", "--domain", domain) ngrok.api("endpoints", "create", "--bindings", "public", "--url", f"https://{domain}", "--traffic-policy-file", "policy.yml") ``` -------------------------------- ### Interact with the ngrok API Source: https://github.com/alexdlaird/pyngrok/blob/develop/README.md Shows how to use the ngrok.api() method to interact with the ngrok agent's API for tasks like reserving domains and creating endpoints with traffic policies. ```python from pyngrok import ngrok domain = "some-domain.ngrok.dev" ngrok.api("reserved-domains", "create", "--domain", domain) ngrok.api("endpoints", "create", "--bindings", "public", "--url", f"https://{domain}", "--traffic-policy-file", "policy.yml") ``` -------------------------------- ### Connect to Server via ngrok Tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst This Python code demonstrates how to connect to a server's socket address through an ngrok tunnel, send a message, and receive a response. Ensure you have a running ngrok tunnel configured with the correct host and port. ```python # Connect to the server with the socket via your ngrok tunnel server_address = (host, port) sock.connect(server_address) print(f"Connected to {host}:{port}") # Send the message message = "ping" print(f"Sending: {message}") sock.sendall(message.encode("utf-8")) # Await a response data_received = 0 data_expected = len(message) while data_received < data_expected: data = sock.recv(1024) data_received += len(data) print("Received: {data}".format(data=data.decode("utf-8"))) sock.close() ``` -------------------------------- ### Expose ngrok Web Inspector Port in Docker Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Run the pyngrok Docker container and expose port 4040 to access the ngrok web inspector. ```shell docker run --env-file .env -p 4040:4040 -it alexdlaird/pyngrok ``` -------------------------------- ### FastAPI Integration with pyngrok Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Configure your FastAPI app to use ngrok for tunneling by setting the USE_NGROK environment variable and initializing the tunnel. ```python import os import sys from fastapi import FastAPI from fastapi.logger import logger from pydantic import BaseSettings class Settings(BaseSettings): # ... Implement the rest of your FastAPI settings BASE_URL = "http://localhost:8000" USE_NGROK = os.environ.get("USE_NGROK", "False") == "True" settings = Settings() def init_webhooks(base_url): # ... Implement updates necessary so webhooks use `public_url` from ngrok pass # Initialize the FastAPI app for a simple web server app = FastAPI() if settings.USE_NGROK: # Only import pyngrok and install if we're actually going to use it from pyngrok import ngrok # Get the dev server port (defaults to 8000 for Uvicorn, can be overridden with `--port` # when starting the server port = sys.argv[sys.argv.index("--port") + 1] if "--port" in sys.argv else "8000" # Open a ngrok tunnel to the dev server public_url = ngrok.connect(port).public_url logger.info(f"ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\"") # Update any base URLs or webhooks to use the public ngrok URL settings.BASE_URL = public_url init_webhooks(public_url) # ... Implement routers and the rest of your app ``` -------------------------------- ### Open v3 Endpoint Without Config File Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Opens a v3 endpoint directly using pyngrok, specifying upstream URL and bindings. ```python from pyngrok import conf, ngrok pyngrok_config = conf.PyngrokConfig(config_version="3") # Open a v3 endpoint # .ngrok.io" -> "http://localhost:8000"> endpoint = ngrok.connect(upstream={"url": "http://localhost:8000"}, bindings=["public"], pyngrok_config=pyngrok_config) ``` -------------------------------- ### Set Auth Token and API Key Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Configure ngrok with an authentication token and an API key to enable advanced features like multiple concurrent tunnels and internal endpoints. This is the primary method for authenticating and authorizing ngrok. ```python from pyngrok import ngrok # Setting an auth token allows you to open multiple # tunnels at the same time ngrok.set_auth_token("") # Setting an API key allows you to use things like Internal Endpoints ngrok.set_api_key("") # .ngrok.io" -> "http://localhost:80"> ngrok_tunnel1 = ngrok.connect() # .ngrok.io" -> "http://localhost:8000"> ngrok_tunnel2 = ngrok.connect("8000") # "localhost:9000"> internal_endpoint = ngrok.connect(addr="9000", proto="tls", domain="some-endpoint.internal", pooling_enabled=True) ``` -------------------------------- ### Initialize pyngrok Tunnel in Flask App Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Configure your Flask app to use ngrok for a public URL during development. This snippet shows how to set up the USE_NGROK environment variable and initialize the tunnel within the app factory. ```python import os import sys from flask import Flask def init_webhooks(base_url): # ... Implement updates necessary so webhooks use `public_url` from ngrok pass def create_app(): app = Flask(__name__) # Initialize your ngrok settings into Flask app.config.from_mapping( BASE_URL="http://localhost:5000", USE_NGROK=os.environ.get("USE_NGROK", "False") == "True" and os.environ.get("WERKZEUG_RUN_MAIN") != "true" ) if app.config["USE_NGROK"]: # Only import pyngrok and install if we're actually going to use it from pyngrok import ngrok # Get the dev server port (defaults to 5000 for Flask, can be overridden with `--port` # when starting the server port = sys.argv[sys.argv.index("--port") + 1] if "--port" in sys.argv else "5000" # Open a ngrok tunnel to the dev server public_url = ngrok.connect(port).public_url print(f" * ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\"") # Update any base URLs or webhooks to use the public ngrok URL app.config["BASE_URL"] = public_url init_webhooks(public_url) # ... Implement Blueprints and the rest of your app return app ``` -------------------------------- ### Configure Pyngrok with Custom Settings Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Create and set a custom PyngrokConfig object to configure pyngrok interactions, such as setting a log event callback and max logs. This custom config can be passed to methods or set as the default. ```python from pyngrok import conf def log_event_callback(log): print(str(log)) pyngrok_config = conf.PyngrokConfig(log_event_callback=log_event_callback, max_logs=10) conf.set_default(pyngrok_config) ``` -------------------------------- ### TCP Server with pyngrok Tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst This Python script sets up a TCP server and uses pyngrok to create a public tunnel to it. It requires a reserved TCP address and environment variables for host and port. ```python import os import socket from pyngrok import ngrok host = os.environ.get("HOST") port = int(os.environ.get("PORT")) # Create a TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind a local socket to the port server_address = ("", port) sock.bind(server_address) sock.listen(1) # Open a ngrok tunnel to the socket public_url = ngrok.connect(port, "tcp", remote_addr=f"{host}:{port}").public_url print(f"ngrok tunnel \"{public_url}\" -> \"tcp://127.0.0.1:{port}\"") while True: connection = None try: # Wait for a connection print("\nWaiting for a connection ...") connection, client_address = sock.accept() print(f"... connection established from {client_address}") # Receive the message, send a response while True: data = connection.recv(1024) if data: print("Received: {data}".format(data=data.decode("utf-8"))) message = "pong" print(f"Sending: {message}") connection.sendall(message.encode("utf-8")) else: break except KeyboardInterrupt: print(" Shutting down server.") if connection: connection.close() break sock.close() ``` -------------------------------- ### Open Tunnel to Local File Server Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Opens a tunnel to serve local directories via ngrok's built-in fileserver. ```python from pyngrok import ngrok # Open a tunnel to a local file server # .ngrok.io" -> "file:///"> ngrok.connect("file:///") ``` -------------------------------- ### Run ngrok CLI from pyngrok Docker Container Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Execute ngrok commands directly from within the pyngrok Docker container. ```shell docker run \ -e NGROK_AUTHTOKEN=$NGROK_AUTHTOKEN -it alexdlaird/pyngrok \ ngrok http 80 ``` -------------------------------- ### Flask Lambda Route Shim Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst This Python snippet shows how to create a Flask Blueprint to route requests to an AWS Lambda handler. It's useful for local development and testing of Lambda functions. ```python import json from flask import Blueprint, request from lambdas.foo_GET import lambda_function as foo_GET bp = Blueprint("lambda_routes", __name__) @bp.route("/foo") def route_foo(): # This becomes the event in the Lambda handler event = { "someQueryParam": request.args.get("someQueryParam") } return json.dumps(foo_GET.lambda_handler(event, {})) ``` -------------------------------- ### Enable pyngrok Debug Logging Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/troubleshooting.rst Configure Python's logging to capture DEBUG level messages from pyngrok. This is crucial for diagnosing issues by displaying detailed ngrok process information and errors to the console. ```python import logging from pyngrok import ngrok # Setup a logger logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")) logger.addHandler(handler) # Then call the pyngrok method throwing the error, for example ngrok.connect() ``` -------------------------------- ### Open TCP Tunnel for SSH Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/integrations.rst Establishes a TCP tunnel to an SSH server. Requires your ngrok authtoken and the port of the SSH server. ```python import getpass from pyngrok import ngrok, conf print("Enter your authtoken, which can be copied from https://dashboard.ngrok.com/get-started/your-authtoken") conf.get_default().auth_token = getpass.getpass() # Open a TCP ngrok tunnel to the SSH server connection_string = ngrok.connect("22", "tcp").public_url ssh_url, port = connection_string.strip("tcp://").split(":") print(f" * ngrok tunnel available, access with `ssh root@{ssh_url} -p{port}`") ``` -------------------------------- ### Open a Tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Use the `ngrok.connect()` method to open a new tunnel. This method returns an `NgrokTunnel` object which contains the public URL. ```APIDOC ## Open a Tunnel Use the :func:`~pyngrok.ngrok.connect` method to open a tunnel. This method returns a :class:`~pyngrok.ngrok.NgrokTunnel` object, which has a reference to the public URL generated by ``ngrok`` in its :attr:`~pyngrok.ngrok.NgrokTunnel.public_url` attribute. ### Method `pyngrok.ngrok.connect(*args, **kwargs)` ### Parameters - `addr` (str, optional): The local address to tunnel to. Defaults to '80'. - `proto` (str, optional): The protocol to use for the tunnel. Defaults to 'http'. - `name` (str, optional): The name of a tunnel defined in the ngrok config file. - `domain` (str, optional): The custom domain to use for the tunnel. - `pooling_enabled` (bool, optional): Whether to enable load balancing for the tunnel. - `**kwargs`: Additional tunnel configurations supported by ngrok. ### Examples ```python from pyngrok import ngrok # Open a HTTP tunnel on the default port 80 http_tunnel = ngrok.connect() # Open a SSH tunnel ssh_tunnel = ngrok.connect("22", "tcp") # Open a named tunnel from the config file named_tunnel = ngrok.connect(name="my-config-file-tunnel") # Open an Internal Endpoint that's load balanced internal_endpoint = ngrok.connect(addr="9000", domain="some-endpoint.internal", pooling_enabled=True) ``` ### Response - Returns: :class:`~pyngrok.ngrok.NgrokTunnel` - An object representing the active tunnel. ``` -------------------------------- ### Open an SSH tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Opens a TCP tunnel to localhost on port 22, suitable for SSH. ```python from pyngrok import ngrok # Open a SSH tunnel # "localhost:22"> ssh_tunnel = ngrok.connect("22", "tcp") ``` -------------------------------- ### Open a named tunnel from config Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Opens a tunnel defined by a name in the ngrok configuration file. ```python from pyngrok import ngrok # Open a named tunnel from the config file named_tunnel = ngrok.connect(name="my-config-file-tunnel") ``` -------------------------------- ### Set ngrok Config Path with PyngrokConfig Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Specify a custom path for the ngrok configuration file using PyngrokConfig. This allows you to manage ngrok settings from a non-default location. ```python from pyngrok import conf, ngrok conf.get_default().config_path = "/opt/ngrok/config.yml" # .ngrok.io" -> "http://localhost:80"> ngrok_tunnel = ngrok.connect() ``` -------------------------------- ### Open TCP Tunnel to MySQL Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Opens a TCP tunnel to a MySQL service, specifying a reserved TCP address. ```python from pyngrok import ngrok # Open a tunnel to MySQL with a Reserved TCP Address # "localhost:3306"> ngrok.connect("3306", "tcp", remote_addr="1.tcp.ngrok.io:12345") ``` -------------------------------- ### Open an HTTP tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Opens a default HTTP tunnel on port 80. The returned NgrokTunnel object contains the public URL. ```python from pyngrok import ngrok # Open a HTTP tunnel on the default port 80 # .ngrok.io" -> "http://localhost:80"> http_tunnel = ngrok.connect() ``` -------------------------------- ### Register Log Event Callback Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Register a callback function to receive and process ngrok log events. The callback function receives an NgrokLog object. ```python from pyngrok import conf, ngrok def log_event_callback(log): print(str(log)) conf.get_default().log_event_callback = log_event_callback # .ngrok.io" -> "http://localhost:80"> ngrok_tunnel = ngrok.connect() ``` -------------------------------- ### Disconnecting a Tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Shows how to disconnect a specific ngrok tunnel using its public URL. ```python from pyngrok import ngrok # Assuming ngrok_tunnel is an existing NgrokTunnel object # ngrok.disconnect(ngrok_tunnel.public_url) ``` -------------------------------- ### Stop Monitor Thread on Running Process Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Stop the monitor thread for an already running ngrok process using stop_monitor_thread. This is an alternative to disabling it in the configuration. ```python import time from pyngrok import ngrok # .ngrok.io" -> "http://localhost:80"> ngrok_tunnel = ngrok.connect() time.sleep(1) ngrok.get_ngrok_process().stop_monitor_thread() ``` -------------------------------- ### Set ngrok Region with PyngrokConfig Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Override the default ngrok region ('us') by specifying a different region, such as 'au', using PyngrokConfig. This ensures tunnels are opened in the desired geographical location. ```python from pyngrok import conf, ngrok conf.get_default().region = "au" # .au.ngrok.io" -> "http://localhost:80"> ngrok_tunnel = ngrok.connect() ``` -------------------------------- ### Disable Monitor Thread Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Disable the monitor thread to free up resources if event logs are not needed. This can be set in PyngrokConfig. ```python from pyngrok import conf, ngrok conf.get_default().monitor_thread = False # .ngrok.io" -> "http://localhost:80"> ngrok_tunnel = ngrok.connect() ``` -------------------------------- ### Close a Tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Manually close a specific tunnel using the `ngrok.disconnect()` method. Tunnels are also automatically closed when the Python process terminates. ```APIDOC ## Close a Tunnel All open tunnels will automatically be closed when the Python process terminates, but you can also close them manually with :func:`~pyngrok.ngrok.disconnect`. ### Method `pyngrok.ngrok.disconnect(public_url: str)` ### Parameters - `public_url` (str): The public URL of the tunnel to disconnect. ``` -------------------------------- ### Close a specific tunnel Source: https://github.com/alexdlaird/pyngrok/blob/develop/docs/index.rst Manually closes a specific ngrok tunnel. Tunnels are automatically closed on process termination. ```python from pyngrok import ngrok # Disconnect a specific tunnel (example not provided in source, only function call mentioned) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.