ngrok_proxy.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # 配置代理环境的 ngrok 启动
  2. import os
  3. from pyngrok import ngrok, conf
  4. # 配置 ngrok 以使用代理
  5. ngrok_config = conf.PyngrokConfig(
  6. ngrok_path="/usr/local/bin/ngrok", # 根据实际路径调整
  7. config_path="~/.config/ngrok/ngrok.yml"
  8. )
  9. # 设置代理环境变量(如果配置文件中没有设置)
  10. os.environ['HTTP_PROXY'] = 'http://172.16.40.16:7280'
  11. os.environ['HTTPS_PROXY'] = 'http://172.16.40.16:7280'
  12. try:
  13. # 连接 ngrok
  14. public_url = ngrok.connect(8101, "http", pyngrok_config=ngrok_config, bind_tls=True)
  15. print("Public URL:", public_url)
  16. print("Web Interface:", public_url.replace("https://", "http://"))
  17. except Exception as e:
  18. print(f"Ngrok connection failed: {e}")
  19. print("Trying alternative configuration...")
  20. # 备选方案:使用命令行方式
  21. import subprocess
  22. try:
  23. # 使用系统命令启动 ngrok
  24. result = subprocess.run([
  25. 'ngrok', 'http', '8101',
  26. '--config', '~/.config/ngrok/ngrok.yml',
  27. '--log', 'stdout'
  28. ], capture_output=True, text=True, timeout=30)
  29. if result.returncode == 0:
  30. print("Ngrok started via command line")
  31. # 获取 ngrok API 信息
  32. import requests
  33. try:
  34. resp = requests.get('http://localhost:4040/api/tunnels')
  35. tunnels = resp.json()['tunnels']
  36. for tunnel in tunnels:
  37. if tunnel['config']['addr'] == 'http://localhost:8101':
  38. print(f"Public URL: {tunnel['public_url']}")
  39. break
  40. except:
  41. print("Please check ngrok web interface at http://localhost:4040")
  42. else:
  43. print(f"Command failed: {result.stderr}")
  44. except subprocess.TimeoutExpired:
  45. print("Ngrok is starting in background...")
  46. print("Check http://localhost:4040 for tunnel URLs")