Cloudflare.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """
  2. 使用 Cloudflare Tunnel 替代 ngrok
  3. """
  4. import subprocess
  5. import time
  6. import json
  7. import requests
  8. def setup_cloudflare_tunnel(port=8101):
  9. """设置 Cloudflare Tunnel"""
  10. print("🔄 Setting up Cloudflare Tunnel...")
  11. # 1. 下载 cloudflared
  12. download_cmd = [
  13. 'wget', '-O', '/tmp/cloudflared',
  14. 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64'
  15. ]
  16. try:
  17. subprocess.run(download_cmd, check=True, env={
  18. 'https_proxy': 'http://172.16.40.16:7280',
  19. 'http_proxy': 'http://172.16.40.16:7280'
  20. })
  21. subprocess.run(['chmod', '+x', '/tmp/cloudflared'], check=True)
  22. print("✅ Cloudflared downloaded")
  23. except subprocess.CalledProcessError as e:
  24. print(f"❌ Download failed: {e}")
  25. return None
  26. # 2. 启动临时隧道
  27. tunnel_cmd = [
  28. '/tmp/cloudflared', 'tunnel',
  29. '--url', f'http://localhost:{port}',
  30. '--no-autoupdate'
  31. ]
  32. try:
  33. print(f"🚀 Starting tunnel for port {port}...")
  34. process = subprocess.Popen(
  35. tunnel_cmd,
  36. stdout=subprocess.PIPE,
  37. stderr=subprocess.PIPE,
  38. text=True,
  39. env={
  40. 'https_proxy': 'http://172.16.40.16:7280',
  41. 'http_proxy': 'http://172.16.40.16:7280'
  42. }
  43. )
  44. # 等待隧道启动并获取 URL
  45. for _ in range(30): # 等待最多30秒
  46. if process.poll() is not None:
  47. stdout, stderr = process.communicate()
  48. print(f"❌ Process failed: {stderr}")
  49. return None
  50. time.sleep(1)
  51. # 尝试从输出中提取 URL
  52. try:
  53. # 读取一些输出
  54. output = process.stdout.readline()
  55. if 'trycloudflare.com' in output:
  56. url = output.split()[-1]
  57. print(f"✅ Tunnel URL: {url}")
  58. return url, process
  59. except:
  60. continue
  61. print("⏰ Timeout waiting for tunnel URL")
  62. process.terminate()
  63. return None
  64. except Exception as e:
  65. print(f"❌ Failed to start tunnel: {e}")
  66. return None
  67. if __name__ == "__main__":
  68. result = setup_cloudflare_tunnel(8101)
  69. if result:
  70. url, process = result
  71. print(f"🌐 Your service is now accessible at: {url}")
  72. print("Press Ctrl+C to stop the tunnel")
  73. try:
  74. process.wait()
  75. except KeyboardInterrupt:
  76. print("\n🛑 Stopping tunnel...")
  77. process.terminate()