Skip to main content

The ngrok Agent SDK for Python

Project description

The ngrok Agent SDK for Python

PyPI Supported Versions MIT licensed Apache-2.0 licensed Continuous integration Status

Note: This is beta-quality software. Interfaces may change without warning.

ngrok is a globally distributed reverse proxy commonly used for quickly getting a public URL to a service running inside a private network, such as on your local laptop. The ngrok agent is usually deployed inside a private network and is used to communicate with the ngrok cloud service.

This is the ngrok agent in library form, suitable for integrating directly into Python applications. This allows you to quickly build ngrok into your application with no separate process to manage.

If you're looking for the previous agent downloader project, it's over here.

Documentation

A quickstart guide and a full API reference are included in the ngrok-python API documentation.

Quickstart

  1. Install the ngrok-python package from PyPI using pip:
python -m pip install ngrok
  1. After you've installed the package, you'll need an authtoken. Retrieve one on the authtoken page of your ngrok dashboard.

  2. Add the following code block using the connect method to expose your python application at port 9000 on localhost:

import ngrok
tunnel = ngrok.connect(9000, authtoken_from_env=True)
print (f"Ingress established at {tunnel.url()}")

You can find more examples in the /examples directory.

Authorization

To use most of ngrok's features, you'll need an authtoken. To obtain one, sign up for free at ngrok.com and retrieve it from the authtoken page in your ngrok dashboard. Once you have copied your authtoken, you can reference it in several ways.

You can set it in the NGROK_AUTHTOKEN environment variable and pass authtoken_from_env=True to the connect method:

ngrok.connect(authtoken_from_env=True, ...)

Or pass the authtoken directly to the connect method:

ngrok.connect(authtoken=token, ...)

Or set it for all connections with the set_auth_token method:

ngrok.set_auth_token(token)

Connection

The connect method is the easiest way to start an ngrok session and establish a tunnel to a specified address. If an asynchronous runtime is running, the connect method returns a promise that resolves to the public tunnel object.

With no arguments, the connect method will start an HTTP tunnel to localhost port 80:

tunnel = ngrok.connect()

You can pass the port number to forward on localhost:

tunnel = ngrok.connect(4242)

Or you can specify the host and port via a string:

tunnel = ngrok.connect("localhost:4242")

More options can be passed to the connect method to customize the connection:

tunnel = ngrok.connect(8080, basic_auth="ngrok:online1line"})
tunnel = ngrok.connect(8080, oauth_provider="google", oauth_allow_domains="example.com")

The second (optional) argument is the tunnel type, which defaults to http. To create a TCP tunnel:

tunnel = ngrok.connect(25565, "tcp")

Since the options are kwargs, you can also use the ** operator to pass a dictionary for configuration:

options = {"authtoken_from_env":True, "response_header_add":"X-Awesome:yes"}
tunnel = ngrok.connect(8080, **options)

Disconnection

To close a tunnel use the disconnect method with the url of the tunnel to close. If there is an asynchronous runtime running the disconnect method returns a promise that resolves when the call is complete.

ngrok.disconnect(url)

Or omit the url to close all tunnels:

ngrok.disconnect()

The close method on a tunnel will shut it down, and also stop the ngrok session if it is no longer needed. This method returns a promise that resolves when the tunnel is closed.

await tunnel.close()

Listing Tunnels

To list all current non-closed tunnels use the get_tunnels method. If there is an asynchronous runtime running the get_tunnels method returns a promise that resolves to the list of tunnel objects.

tunnels = ngrok.get_tunnels()

Full Configuration

This example shows all the possible configuration items of ngrok.connect:

tunnel = ngrok.connect(
    # session configuration
    addr="localhost:8080",
    authtoken="<authtoken>",
    authtoken_from_env=True,
    session_metadata="Online in One Line",
    # tunnel configuration
    basic_auth=["ngrok:online1line"],
    circuit_breaker=0.1,
    compression=True,
    domain="<domain>",
    ip_restriction_allow_cidrs="0.0.0.0/0",
    ip_restriction_deny_cidrs="10.1.1.1/32",
    metadata="example tunnel metadata from python",
    mutual_tls_cas=load_file("ca.crt"),
    oauth_provider="google",
    oauth_allow_domains=["<domain>"],
    oauth_allow_emails=["<email>"],
    oauth_scopes=["<scope>"],
    oidc_issuer_url="<url>",
    oidc_client_id="<id>",
    oidc_client_secret="<secret>",
    oidc_allow_domains=["<domain>"],
    oidc_allow_emails=["<email>"],
    oidc_scopes=["<scope>"],
    proxy_proto="",  # One of: "", "1", "2"
    request_header_remove="X-Req-Nope",
    response_header_remove="X-Res-Nope",
    request_header_add="X-Req-Yup:true",
    response_header_add="X-Res-Yup:true",
    schemes=["HTTPS"],
    verify_webhook_provider="twilio",
    verify_webhook_secret="asdf",
    websocket_tcp_converter=True,
)

ASGI Runner - Tunnels to Uvicorn, Gunicorn, Django and More, With No Code

Prefix the command line which starts up a Uvicorn or Gunicorn web server with either ngrok-asgi or python -m ngrok. Any TCP or Unix Domain Socket arguments will be used to establish connectivity automatically. There are many command line arguments to configure the Tunnel used, for instance adding --basic-auth ngrok online1line will introduce basic authentication to the ingress tunnel.

Uvicorn

Examples:

ngrok-asgi uvicorn mysite.asgi:application
ngrok-asgi uvicorn mysite.asgi:application --host localhost --port 1234
ngrok-asgi uvicorn mysite.asgi:application --host localhost --port 1234 --basic-auth ngrok online1line
ngrok-asgi uvicorn mysite.asgi:application --uds /tmp/uvicorn.sock

# Can use the module name as well, such as:
python -m ngrok uvicorn mysite.asgi:application --oauth-provider google --allow-emails bob@example.com

Gunicorn

Examples:

ngrok-asgi gunicorn mysite.asgi:application -k uvicorn.workers.UvicornWorker
ngrok-asgi gunicorn mysite.asgi:application -k uvicorn.workers.UvicornWorker --webhook-verification twilio s3cr3t
ngrok-asgi gunicorn mysite.asgi:application -k uvicorn.workers.UvicornWorker --bind localhost:1234
ngrok-asgi gunicorn mysite.asgi:application -k uvicorn.workers.UvicornWorker --bind unix:/tmp/gunicorn.sock

# Can use the module name as well, such as:
python -m ngrok gunicorn mysite.asgi:application -k uvicorn.workers.UvicornWorker --response-header X-Awesome True

Examples

Frameworks

Machine Learning

Tunnel Types

Unix Sockets

You may also choose to use Unix Sockets instead of TCP. You can view an example of this here.

A socket address may be passed directly into the tunnel forward() call as well by prefixing the address with unix:, for example unix:/tmp/socket-123.

Builders

For more control over Sessions and Tunnels, the builder classes can be used.

A minimal example using the builder class looks like the following:

async def create_tunnel():
    session = await ngrok.NgrokSessionBuilder().authtoken_from_env().connect()
    tunnel = await session.http_endpoint().listen()
    print (f"Ingress established at {tunnel.url()}")
    tunnel.forward("localhost:9000")

See here for a Full Configuration Example

Platform Support

Pre-built binaries are provided on PyPI for the following platforms:

OS i686 x64 aarch64 arm
Windows *
MacOS
Linux
Linux musl
FreeBSD *

ngrok-python, and ngrok-rust which it depends on, are open source, so it may be possible to build them for other platforms.

  • Windows-aarch64 will be supported after the next release of Ring.
  • FreeBSD-x64 is built by the release process, but PyPI won't accept BSD flavors.

Dependencies

This project relies on PyO3, an excellent system to ease development and building of Rust plugins for Python.

Thank you to OpenIoTHub for handing over the ngrok name on PyPI.

Change Log

Changes are tracked in CHANGELOG.md.

License

This project is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in ngrok-python by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

ngrok-0.10.1-cp37-abi3-win_amd64.whl (2.8 MB view hashes)

Uploaded CPython 3.7+ Windows x86-64

ngrok-0.10.1-cp37-abi3-win32.whl (2.4 MB view hashes)

Uploaded CPython 3.7+ Windows x86

ngrok-0.10.1-cp37-abi3-musllinux_1_2_x86_64.whl (2.7 MB view hashes)

Uploaded CPython 3.7+ musllinux: musl 1.2+ x86-64

ngrok-0.10.1-cp37-abi3-musllinux_1_2_aarch64.whl (2.6 MB view hashes)

Uploaded CPython 3.7+ musllinux: musl 1.2+ ARM64

ngrok-0.10.1-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.7 MB view hashes)

Uploaded CPython 3.7+ manylinux: glibc 2.17+ x86-64

ngrok-0.10.1-cp37-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl (2.3 MB view hashes)

Uploaded CPython 3.7+ manylinux: glibc 2.17+ ARMv7l

ngrok-0.10.1-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (4.2 MB view hashes)

Uploaded CPython 3.7+ manylinux: glibc 2.17+ ARM64

ngrok-0.10.1-cp37-abi3-macosx_11_0_arm64.whl (2.4 MB view hashes)

Uploaded CPython 3.7+ macOS 11.0+ ARM64

ngrok-0.10.1-cp37-abi3-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl (5.0 MB view hashes)

Uploaded CPython 3.7+ macOS 10.9+ universal2 (ARM64, x86-64) macOS 10.9+ x86-64 macOS 11.0+ ARM64

ngrok-0.10.1-cp37-abi3-macosx_10_7_x86_64.whl (2.6 MB view hashes)

Uploaded CPython 3.7+ macOS 10.7+ x86-64

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page