0
# Installation and Binary Management
1
2
Automatic ngrok binary download, installation, and management with support for multiple ngrok versions and platform detection.
3
4
## Capabilities
5
6
### Basic Installation
7
8
Automatic ngrok binary installation with version management.
9
10
```python { .api }
11
def install_ngrok(pyngrok_config=None):
12
"""
13
Download, install, and initialize ngrok for the given config.
14
If ngrok and its config are already installed, does nothing.
15
16
Parameters:
17
- pyngrok_config (PyngrokConfig, optional): Configuration override
18
"""
19
```
20
21
**Usage Examples:**
22
23
```python
24
from pyngrok import ngrok, conf
25
26
# Install with default configuration
27
ngrok.install_ngrok()
28
29
# Install with custom configuration
30
custom_config = conf.PyngrokConfig(
31
ngrok_path="/usr/local/bin/ngrok",
32
ngrok_version="v3"
33
)
34
ngrok.install_ngrok(custom_config)
35
36
# Installation is idempotent - safe to call multiple times
37
ngrok.install_ngrok() # Does nothing if already installed
38
```
39
40
### Version Management
41
42
Get version information and update ngrok binary.
43
44
```python { .api }
45
def get_version(pyngrok_config=None):
46
"""
47
Get tuple with ngrok and pyngrok versions.
48
49
Parameters:
50
- pyngrok_config (PyngrokConfig, optional): Configuration override
51
52
Returns:
53
tuple[str, str]: (ngrok_version, pyngrok_version)
54
"""
55
56
def update(pyngrok_config=None):
57
"""
58
Update ngrok binary if an update is available.
59
60
Parameters:
61
- pyngrok_config (PyngrokConfig, optional): Configuration override
62
63
Returns:
64
str: Result from the ngrok update command
65
"""
66
```
67
68
**Usage Examples:**
69
70
```python
71
from pyngrok import ngrok
72
73
# Check current versions
74
ngrok_version, pyngrok_version = ngrok.get_version()
75
print(f"ngrok version: {ngrok_version}")
76
print(f"pyngrok version: {pyngrok_version}")
77
78
# Update ngrok if newer version available
79
try:
80
update_result = ngrok.update()
81
print(f"Update result: {update_result}")
82
except Exception as e:
83
print(f"Update failed: {e}")
84
```
85
86
### Authentication Setup
87
88
Configure authentication tokens and API keys for ngrok features.
89
90
```python { .api }
91
def set_auth_token(token, pyngrok_config=None):
92
"""
93
Set ngrok auth token in config file for advanced features.
94
Installs ngrok if not already present.
95
96
Parameters:
97
- token (str): The auth token to set
98
- pyngrok_config (PyngrokConfig, optional): Configuration override
99
"""
100
101
def set_api_key(key, pyngrok_config=None):
102
"""
103
Set ngrok API key in config file for advanced features.
104
Installs ngrok if not already present.
105
106
Parameters:
107
- key (str): The API key to set
108
- pyngrok_config (PyngrokConfig, optional): Configuration override
109
"""
110
```
111
112
**Usage Examples:**
113
114
```python
115
from pyngrok import ngrok
116
117
# Set auth token for multiple concurrent tunnels
118
ngrok.set_auth_token("your_ngrok_authtoken_here")
119
120
# Set API key for advanced features (v3 only)
121
ngrok.set_api_key("your_ngrok_api_key_here")
122
123
# Now you can create multiple tunnels
124
tunnel1 = ngrok.connect("8000")
125
tunnel2 = ngrok.connect("9000")
126
tunnel3 = ngrok.connect("22", "tcp")
127
```
128
129
### Low-Level Installation Functions
130
131
Direct control over ngrok installation process.
132
133
```python { .api }
134
def get_default_ngrok_dir():
135
"""
136
Get the default ngrok directory for current system.
137
138
Returns:
139
str: The default ngrok directory path
140
"""
141
142
def get_system():
143
"""
144
Get the friendly name of the current operating system.
145
146
Returns:
147
str: OS name ("darwin", "windows", "linux", "freebsd")
148
149
Raises:
150
PyngrokNgrokInstallError: When platform is not supported
151
"""
152
153
def get_arch():
154
"""
155
Get the architecture of the current system.
156
157
Returns:
158
str: Architecture name ("i386", "x86_64", "x86_64_arm", etc.)
159
"""
160
161
def install_ngrok(ngrok_path, ngrok_version="v3", **kwargs):
162
"""
163
Download and install ngrok binary to specified path.
164
165
Parameters:
166
- ngrok_path (str): Path where ngrok binary will be installed
167
- ngrok_version (str): Major version ("v2" or "v3")
168
- **kwargs: Additional options passed to download function
169
170
Raises:
171
PyngrokError: When ngrok_version is not supported
172
PyngrokNgrokInstallError: When installation fails
173
"""
174
```
175
176
**Usage Examples:**
177
178
```python
179
from pyngrok import installer
180
181
# Get system information
182
print(f"Default ngrok directory: {installer.get_default_ngrok_dir()}")
183
print(f"System: {installer.get_system()}")
184
print(f"Architecture: {installer.get_arch()}")
185
186
# Install ngrok to custom location
187
custom_path = "/opt/ngrok/ngrok"
188
installer.install_ngrok(custom_path, ngrok_version="v3")
189
190
# Install specific version with custom timeout
191
installer.install_ngrok(
192
"/usr/local/bin/ngrok",
193
ngrok_version="v2",
194
timeout=30 # 30 second download timeout
195
)
196
```
197
198
### Configuration File Management
199
200
Manage ngrok configuration files and validation.
201
202
```python { .api }
203
def get_ngrok_config(config_path, use_cache=True, ngrok_version="v3", config_version="2"):
204
"""
205
Get ngrok config from the given path.
206
207
Parameters:
208
- config_path (str): Path to ngrok config file
209
- use_cache (bool): Whether to use cached config if available
210
- ngrok_version (str): Major version of ngrok
211
- config_version (str): ngrok config version
212
213
Returns:
214
dict: The ngrok configuration
215
"""
216
217
def install_default_config(config_path, data=None, ngrok_version="v3", config_version="2"):
218
"""
219
Install default config to the specified path.
220
221
Parameters:
222
- config_path (str): Path where config should be installed
223
- data (dict, optional): Additional config data to include
224
- ngrok_version (str): Major version of ngrok
225
- config_version (str): ngrok config version
226
"""
227
228
def validate_config(data):
229
"""
230
Validate config data for compatibility with pyngrok.
231
232
Parameters:
233
- data (dict): Config data to validate
234
235
Raises:
236
PyngrokError: When config contains incompatible settings
237
"""
238
```
239
240
**Usage Examples:**
241
242
```python
243
from pyngrok import installer, conf
244
import os
245
246
# Get default config path
247
config = conf.get_default()
248
config_path = conf.get_config_path(config)
249
250
# Read existing config
251
if os.path.exists(config_path):
252
ngrok_config = installer.get_ngrok_config(config_path)
253
print(f"Current config: {ngrok_config}")
254
255
# Install default config with custom data
256
custom_data = {
257
"authtoken": "your_token_here",
258
"region": "eu"
259
}
260
installer.install_default_config(config_path, custom_data)
261
262
# Validate config before using
263
test_config = {
264
"web_addr": "localhost:4040",
265
"log_level": "info"
266
}
267
try:
268
installer.validate_config(test_config)
269
print("Config is valid")
270
except Exception as e:
271
print(f"Config validation failed: {e}")
272
```
273
274
### Platform and Version Detection
275
276
Utilities for detecting platform and version compatibility.
277
278
```python { .api }
279
def get_ngrok_bin():
280
"""
281
Get ngrok executable name for current system.
282
283
Returns:
284
str: Executable name ("ngrok" on Unix, "ngrok.exe" on Windows)
285
"""
286
287
def get_ngrok_cdn_url(ngrok_version):
288
"""
289
Get CDN download URL for current platform and ngrok version.
290
291
Parameters:
292
- ngrok_version (str): Major version ("v2" or "v3")
293
294
Returns:
295
str: CDN download URL for current platform
296
297
Raises:
298
PyngrokNgrokInstallError: When platform is not supported
299
"""
300
```
301
302
**Usage Examples:**
303
304
```python
305
from pyngrok import installer
306
307
# Get platform-specific executable name
308
executable = installer.get_ngrok_bin()
309
print(f"ngrok executable: {executable}")
310
311
# Get download URLs for different versions
312
v2_url = installer.get_ngrok_cdn_url("v2")
313
v3_url = installer.get_ngrok_cdn_url("v3")
314
315
print(f"ngrok v2 download URL: {v2_url}")
316
print(f"ngrok v3 download URL: {v3_url}")
317
```
318
319
### Installation Constants
320
321
Platform and version information available as module constants.
322
323
```python { .api }
324
# Platform download URLs
325
PLATFORMS: dict # v2 platform-specific download URLs
326
PLATFORMS_V3: dict # v3 platform-specific download URLs
327
328
# Supported configurations
329
UNIX_BINARIES: list # List of Unix-like OS names
330
SUPPORTED_NGROK_VERSIONS: list # List of supported ngrok versions
331
332
# Download settings
333
DEFAULT_DOWNLOAD_TIMEOUT: int # Default download timeout in seconds
334
DEFAULT_RETRY_COUNT: int # Default number of download retries
335
336
# Thread synchronization
337
config_file_lock: threading.RLock # Lock for config file operations
338
```
339
340
**Usage Examples:**
341
342
```python
343
from pyngrok import installer
344
345
# Check supported versions
346
print(f"Supported versions: {installer.SUPPORTED_NGROK_VERSIONS}")
347
348
# Check if current platform is Unix-like
349
system = installer.get_system()
350
is_unix = system in installer.UNIX_BINARIES
351
print(f"Unix-like system: {is_unix}")
352
353
# Access platform URLs
354
print(f"Available v3 platforms: {list(installer.PLATFORMS_V3.keys())}")
355
```
356
357
### Error Handling and Troubleshooting
358
359
Common installation error scenarios and handling.
360
361
**Usage Examples:**
362
363
```python
364
from pyngrok import ngrok, installer
365
from pyngrok.exception import PyngrokNgrokInstallError, PyngrokError
366
367
# Handle installation errors
368
try:
369
ngrok.install_ngrok()
370
except PyngrokNgrokInstallError as e:
371
print(f"Installation failed: {e}")
372
# Try manual installation or check network connectivity
373
except PyngrokError as e:
374
print(f"General pyngrok error: {e}")
375
376
# Verify installation
377
try:
378
version = ngrok.get_version()
379
print(f"Installation successful: {version}")
380
except Exception as e:
381
print(f"Installation verification failed: {e}")
382
383
# Handle platform compatibility
384
try:
385
system = installer.get_system()
386
arch = installer.get_arch()
387
print(f"Platform: {system}-{arch}")
388
except PyngrokNgrokInstallError as e:
389
print(f"Unsupported platform: {e}")
390
391
# Custom installation with error handling
392
def safe_install(custom_path, version="v3", max_retries=3):
393
"""Install ngrok with retry logic"""
394
for attempt in range(max_retries):
395
try:
396
installer.install_ngrok(custom_path, ngrok_version=version)
397
print(f"Installation successful on attempt {attempt + 1}")
398
return
399
except Exception as e:
400
print(f"Attempt {attempt + 1} failed: {e}")
401
if attempt == max_retries - 1:
402
print("All installation attempts failed")
403
raise
404
405
# Use safe installation
406
safe_install("/opt/ngrok/ngrok")
407
```