-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlaunch_tunnel.py
More file actions
75 lines (66 loc) · 2.63 KB
/
Copy pathlaunch_tunnel.py
File metadata and controls
75 lines (66 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import subprocess
import time
import select
import re
import os
tunnel_file = "tunnel_url.txt"
is_running = False
try:
pgrep_proc = subprocess.run(["pgrep", "-f", "cloudflared tunnel"], capture_output=True, text=True)
if pgrep_proc.stdout.strip():
is_running = True
except Exception:
pass
if is_running and os.path.exists(tunnel_file):
with open(tunnel_file, "r") as f:
cf_url = f.read().strip()
print("=======================================================")
print(f"Tunnel is already active. Reuse your existing link:\n{cf_url}")
print("=======================================================")
else:
# Clean up any potential dead/zombie processes first
subprocess.run(["pkill", "-f", "cloudflared"], capture_output=True)
time.sleep(1)
print("Starting Global Cloudflare Tunnel on Port 8000 in a detached session...")
# Dynamically locate the cloudflared binary to handle duplicate clone folder nesting robustly
cf_path = "./cloudflared"
if not os.path.exists(cf_path):
if os.path.exists("../cloudflared"):
cf_path = "../cloudflared"
else:
import shutil
system_cf = shutil.which("cloudflared")
if system_cf:
cf_path = system_cf
# Use os.setsid to completely detach the process group so stopping other cells won't kill the tunnel!
cf_proc = subprocess.Popen(
[cf_path, "tunnel", "--url", "http://127.0.0.1:8000"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
preexec_fn=os.setsid
)
# Parse URL non-blockingly
cf_url = "Connecting..."
start_cf = time.time()
while time.time() - start_cf < 15:
rlist, _, _ = select.select([cf_proc.stdout], [], [], 0.1)
if rlist:
line = cf_proc.stdout.readline()
if line:
match = re.search(r"https://[a-zA-Z0-9-]+.trycloudflare.com", line)
if match:
cf_url = match.group(0)
break
else:
time.sleep(0.1)
if "trycloudflare.com" in cf_url:
with open(tunnel_file, "w") as f:
f.write(cf_url)
print("Waiting 5 seconds for global DNS propagation...")
time.sleep(5)
print("\n=======================================================")
print(f"Success! Click the link below to keep it open in your browser:\n{cf_url}")
print("=======================================================")
else:
print("Failed to parse Cloudflare Tunnel URL. Please re-run this script.")