0
# Tunnel Management
1
2
Core functionality for creating, listing, and managing ngrok tunnels including HTTP, TCP, and TLS tunnels with full configuration support and automatic binary management.
3
4
## Capabilities
5
6
### Creating Tunnels
7
8
Establishes new ngrok tunnels with flexible configuration options supporting various protocols and tunnel definitions.
9
10
```python { .api }
11
def connect(addr=None, proto=None, name=None, pyngrok_config=None, **options):
12
"""
13
Establish a new ngrok tunnel for the given protocol to the given port.
14
15
Parameters:
16
- addr (str, optional): Local port to forward traffic to, or local directory/network address. Defaults to "80"
17
- proto (str, optional): Tunnel protocol ("http", "tcp", "tls"). Defaults to "http"
18
- name (str, optional): Friendly name for the tunnel or name of tunnel definition in ngrok config
19
- pyngrok_config (PyngrokConfig, optional): Configuration override
20
- **options: Additional tunnel configuration options
21
22
Returns:
23
NgrokTunnel: The created tunnel object
24
25
Raises:
26
PyngrokError: When tunnel definition is invalid or response lacks public_url
27
"""
28
```
29
30
**Usage Examples:**
31
32
```python
33
from pyngrok import ngrok
34
35
# HTTP tunnel on default port 80
36
tunnel = ngrok.connect()
37
38
# HTTP tunnel on specific port
39
tunnel = ngrok.connect("8000")
40
41
# TCP tunnel for SSH
42
ssh_tunnel = ngrok.connect("22", "tcp")
43
44
# HTTP tunnel with custom domain (requires auth token)
45
tunnel = ngrok.connect("3000", subdomain="my-app")
46
47
# HTTPS-only tunnel
48
tunnel = ngrok.connect("8080", bind_tls=True)
49
50
# Named tunnel from config file
51
tunnel = ngrok.connect(name="my-tunnel-config")
52
53
# File serving
54
tunnel = ngrok.connect("file:///path/to/files", "http")
55
```
56
57
### Disconnecting Tunnels
58
59
Closes specific ngrok tunnels by their public URL.
60
61
```python { .api }
62
def disconnect(public_url, pyngrok_config=None):
63
"""
64
Disconnect the ngrok tunnel for the given URL.
65
66
Parameters:
67
- public_url (str): The public URL of the tunnel to disconnect
68
- pyngrok_config (PyngrokConfig, optional): Configuration override
69
"""
70
```
71
72
**Usage Examples:**
73
74
```python
75
from pyngrok import ngrok
76
77
# Create and then disconnect a tunnel
78
tunnel = ngrok.connect("8000")
79
print(f"Tunnel created: {tunnel.public_url}")
80
81
# Disconnect by public URL
82
ngrok.disconnect(tunnel.public_url)
83
```
84
85
### Listing Active Tunnels
86
87
Retrieves all currently active ngrok tunnels with their configuration and metrics.
88
89
```python { .api }
90
def get_tunnels(pyngrok_config=None):
91
"""
92
Get a list of active ngrok tunnels.
93
94
Parameters:
95
- pyngrok_config (PyngrokConfig, optional): Configuration override
96
97
Returns:
98
list[NgrokTunnel]: List of active tunnel objects
99
100
Raises:
101
PyngrokError: When response is invalid or lacks public_url
102
"""
103
```
104
105
**Usage Examples:**
106
107
```python
108
from pyngrok import ngrok
109
110
# Create some tunnels
111
http_tunnel = ngrok.connect("8000")
112
tcp_tunnel = ngrok.connect("22", "tcp")
113
114
# List all active tunnels
115
tunnels = ngrok.get_tunnels()
116
for tunnel in tunnels:
117
print(f"Name: {tunnel.name}")
118
print(f"Public URL: {tunnel.public_url}")
119
print(f"Local Address: {tunnel.config['addr']}")
120
print(f"Protocol: {tunnel.proto}")
121
print("---")
122
```
123
124
### Killing All Processes
125
126
Terminates all ngrok processes and clears tunnel state.
127
128
```python { .api }
129
def kill(pyngrok_config=None):
130
"""
131
Terminate all ngrok processes for the given config's ngrok_path.
132
133
Parameters:
134
- pyngrok_config (PyngrokConfig, optional): Configuration override
135
"""
136
```
137
138
**Usage Examples:**
139
140
```python
141
from pyngrok import ngrok
142
143
# Create some tunnels
144
ngrok.connect("8000")
145
ngrok.connect("9000")
146
147
# Terminate all ngrok processes and clear tunnels
148
ngrok.kill()
149
150
# Verify no tunnels remain
151
tunnels = ngrok.get_tunnels() # Will start new process
152
print(len(tunnels)) # Should be 0
153
```
154
155
### Tunnel Information and Metrics
156
157
Each tunnel provides detailed information and metrics through the NgrokTunnel object.
158
159
```python { .api }
160
class NgrokTunnel:
161
"""
162
Container for ngrok tunnel information and operations.
163
"""
164
id: str # Tunnel ID
165
name: str # Tunnel name
166
proto: str # Protocol (http, tcp, tls)
167
uri: str # API URI for tunnel operations
168
public_url: str # Public ngrok URL
169
config: dict # Tunnel configuration
170
metrics: dict # Traffic metrics
171
data: dict # Raw tunnel data from ngrok
172
pyngrok_config: PyngrokConfig # Configuration used
173
api_url: str # ngrok API URL
174
175
def refresh_metrics(self):
176
"""
177
Get the latest metrics for the tunnel and update the metrics variable.
178
179
Raises:
180
PyngrokError: When the API does not return metrics
181
"""
182
```
183
184
**Usage Examples:**
185
186
```python
187
from pyngrok import ngrok
188
189
# Create tunnel and inspect properties
190
tunnel = ngrok.connect("8000")
191
192
print(f"Tunnel ID: {tunnel.id}")
193
print(f"Name: {tunnel.name}")
194
print(f"Protocol: {tunnel.proto}")
195
print(f"Public URL: {tunnel.public_url}")
196
print(f"Local Address: {tunnel.config['addr']}")
197
198
# Access metrics
199
print(f"Requests Count: {tunnel.metrics.get('conns', {}).get('count', 0)}")
200
print(f"Bytes In: {tunnel.metrics.get('http', {}).get('bytes_in', 0)}")
201
202
# Refresh metrics to get latest data
203
tunnel.refresh_metrics()
204
print(f"Updated Requests: {tunnel.metrics.get('conns', {}).get('count', 0)}")
205
```
206
207
## Advanced Configuration Options
208
209
Tunnels support extensive configuration through keyword arguments:
210
211
```python
212
from pyngrok import ngrok
213
214
# HTTP tunnel with custom configuration
215
tunnel = ngrok.connect(
216
addr="8000",
217
proto="http",
218
subdomain="my-app", # Custom subdomain (requires auth)
219
hostname="example.com", # Custom hostname (requires auth)
220
auth="user:pass", # HTTP basic auth
221
bind_tls=True, # HTTPS only
222
inspect=False, # Disable request inspection
223
host_header="rewrite" # Host header handling
224
)
225
226
# TCP tunnel with configuration
227
tcp_tunnel = ngrok.connect(
228
addr="22",
229
proto="tcp",
230
remote_addr="1.tcp.ngrok.io:12345" # Fixed remote address
231
)
232
```
233
234
## Error Handling
235
236
Tunnel operations can raise various exceptions that should be handled appropriately:
237
238
```python
239
from pyngrok import ngrok
240
from pyngrok.exception import PyngrokError, PyngrokNgrokError
241
242
try:
243
tunnel = ngrok.connect("8000", subdomain="taken-subdomain")
244
except PyngrokNgrokError as e:
245
print(f"ngrok error: {e}")
246
print(f"Error details: {e.ngrok_error}")
247
except PyngrokError as e:
248
print(f"pyngrok error: {e}")
249
250
try:
251
ngrok.disconnect("https://nonexistent.ngrok.io")
252
except Exception:
253
# Disconnect silently handles non-existent tunnels
254
pass
255
```