| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- # 配置代理环境的 ngrok 启动
- import os
- from pyngrok import ngrok, conf
- # 配置 ngrok 以使用代理
- ngrok_config = conf.PyngrokConfig(
- ngrok_path="/usr/local/bin/ngrok", # 根据实际路径调整
- config_path="~/.config/ngrok/ngrok.yml"
- )
- # 设置代理环境变量(如果配置文件中没有设置)
- os.environ['HTTP_PROXY'] = 'http://172.16.40.16:7280'
- os.environ['HTTPS_PROXY'] = 'http://172.16.40.16:7280'
- try:
- # 连接 ngrok
- public_url = ngrok.connect(8101, "http", pyngrok_config=ngrok_config, bind_tls=True)
- print("Public URL:", public_url)
- print("Web Interface:", public_url.replace("https://", "http://"))
- except Exception as e:
- print(f"Ngrok connection failed: {e}")
- print("Trying alternative configuration...")
-
- # 备选方案:使用命令行方式
- import subprocess
- try:
- # 使用系统命令启动 ngrok
- result = subprocess.run([
- 'ngrok', 'http', '8101',
- '--config', '~/.config/ngrok/ngrok.yml',
- '--log', 'stdout'
- ], capture_output=True, text=True, timeout=30)
-
- if result.returncode == 0:
- print("Ngrok started via command line")
- # 获取 ngrok API 信息
- import requests
- try:
- resp = requests.get('http://localhost:4040/api/tunnels')
- tunnels = resp.json()['tunnels']
- for tunnel in tunnels:
- if tunnel['config']['addr'] == 'http://localhost:8101':
- print(f"Public URL: {tunnel['public_url']}")
- break
- except:
- print("Please check ngrok web interface at http://localhost:4040")
- else:
- print(f"Command failed: {result.stderr}")
- except subprocess.TimeoutExpired:
- print("Ngrok is starting in background...")
- print("Check http://localhost:4040 for tunnel URLs")
|