-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
225 lines (202 loc) · 9.28 KB
/
main.py
File metadata and controls
225 lines (202 loc) · 9.28 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python3
import os, sys, time, threading, http.server, socketserver, subprocess, json, re, signal
from pathlib import Path
# ---------------- Colors ----------------
class Colors:
HEADER='\033[95m'; BLUE='\033[94m'; CYAN='\033[96m'; GREEN='\033[92m'
YELLOW='\033[93m'; RED='\033[91m'; BOLD='\033[1m'; ENDC='\033[0m'
# ---------------- Directories ----------------
TOOLS_DIR = Path(os.getcwd()) / "tools"
WWW_DIR = Path(os.getcwd()) / "www"
CONFIG_FILE = Path(os.getcwd()) / "autohost_config.json"
TOOLS_DIR.mkdir(exist_ok=True)
WWW_DIR.mkdir(exist_ok=True)
# ---------------- Tunnel Services ----------------
TUNNEL_CONFIG = {
"1":{"name":"ngrok","auth_required":True,"install_cmd":"sudo apt install -y ngrok","cli":"ngrok"},
"2":{"name":"localtunnel (lt)","auth_required":False,"install_cmd":"sudo npm install -g localtunnel","cli":"lt"},
"3":{"name":"cloudflared","auth_required":False,"install_cmd":"sudo apt install -y cloudflared","cli":"cloudflared"},
"4":{"name":"Serveo (SSH)","auth_required":False,"install_cmd":None,"cli":"ssh"},
"5":{"name":"Pinggy (SSH)","auth_required":False,"install_cmd":None,"cli":"ssh"},
"6":{"name":"Localxpose (lx)","auth_required":False,"install_cmd":"curl -s https://get.localxpose.io | bash","cli":"lx"},
}
# ---------------- Global for tunnel processes ----------------
running_tunnels = []
# ---------------- Banner ----------------
def print_banner():
banner = [
" __ .__ __ ",
"_____ __ ___/ |_ ____ | |__ ____ _______/ |_ ",
r"\__ \ | | \ __\/ _ \| | \ / _ \/ ___/\ __\ ",
" / __ \\| | /| | ( <_> ) Y ( <_> )___ \\ | | ",
"(____ /____/ |__| \\____/|___| /\\____/____ > |__| ",
" \\/ \\/ \\/ "
]
subtitle=" AutoHost - Localhost Tunneling"
tagline=' "Expose your local server to the world seamlessly!"'
print()
for line in banner: print(f"{Colors.RED}{Colors.BOLD}{line}{Colors.ENDC}")
print(f"{Colors.YELLOW}{Colors.BOLD}{subtitle}{Colors.ENDC}")
print(f"{Colors.CYAN}{tagline}{Colors.ENDC}\n")
# ---------------- Config ----------------
def load_config():
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE,"r") as f:
return json.load(f)
except: return {}
return {}
def save_config(data):
with open(CONFIG_FILE,"w") as f:
json.dump(data,f)
# ---------------- Tool Check & Install ----------------
def check_cli(choice):
cli_name = TUNNEL_CONFIG[choice]["cli"]
try:
subprocess.run([cli_name,"--version"],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
return True
except:
install_cmd = TUNNEL_CONFIG[choice]["install_cmd"]
if install_cmd:
print(f"{Colors.YELLOW}[INFO] {cli_name} not found, attempting to install...{Colors.ENDC}")
try:
subprocess.run(install_cmd,shell=True,check=True)
print(f"{Colors.GREEN}[INFO] {cli_name} installed successfully!{Colors.ENDC}")
return True
except subprocess.CalledProcessError:
print(f"{Colors.RED}[ERROR] Failed to install {cli_name}.{Colors.ENDC}")
else:
print(f"{Colors.RED}[WARN] {cli_name} not found. Please install manually.{Colors.ENDC}")
return False
# ---------------- Configure ngrok ----------------
def configure_ngrok_token(token):
try:
subprocess.run(["ngrok","config","add-authtoken",token],check=True)
print(f"{Colors.GREEN}[INFO] ngrok token configured!{Colors.ENDC}")
return True
except Exception as e:
print(f"{Colors.RED}[ERROR] Failed token configuration: {e}{Colors.ENDC}")
return False
# ---------------- HTTP Server ----------------
def start_http_server(port,www_path):
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self,*args,**kwargs):
super().__init__(*args,directory=www_path,**kwargs)
server = socketserver.TCPServer(("", port), Handler)
t = threading.Thread(target=server.serve_forever,daemon=True)
t.start()
print(f"{Colors.GREEN}[INFO] Serving '{www_path}' at http://127.0.0.1:{port}{Colors.ENDC}")
return server
# ---------------- Create Animated Index ----------------
def create_index(www_path):
index_file = Path(www_path)/"index.html"
if not index_file.exists():
index_file.write_text("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AutoHost</title>
<style>
body { margin:0; padding:0; display:flex; justify-content:center; align-items:center; height:100vh;
background: linear-gradient(270deg,#ff4d4d,#1a1aff,#4dff4d,#ff4dd9); background-size: 800% 800%;
animation: gradientBG 15s ease infinite; font-family: 'Press Start 2P', cursive; color:#fff; text-align:center;}
@keyframes gradientBG {0%{background-position:0% 50%;}50%{background-position:100% 50%;}100%{background-position:0% 50%;}}
h1 { font-size:2.5em; animation: bounce 2s infinite; text-shadow:2px 2px 10px #000; }
@keyframes bounce {0%,100%{transform:translateY(0);}50%{transform:translateY(-20px);}}
p { font-size:1em; margin-top:20px; animation: fadeIn 3s ease-in-out infinite alternate; }
@keyframes fadeIn {from{opacity:0.5;}to{opacity:1;}}
</style>
</head>
<body>
<div>
<h1>Welcome to AutoHost!</h1>
<p>Expose your local server to the world seamlessly.</p>
<p>🚀 Start your tunnel and get your public URL instantly!</p>
</div>
</body>
</html>
""")
print(f"{Colors.GREEN}[INFO] Catchy landing page created at {index_file}{Colors.ENDC}")
# ---------------- Tunnel Runner ----------------
def run_tunnel(command, service_name):
global running_tunnels
process=None
url_regex = re.compile(r"https?://\S+")
try:
print(f"{Colors.CYAN}[INFO] Starting {service_name} tunnel... CTRL+C to stop.{Colors.ENDC}")
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, preexec_fn=os.setsid)
running_tunnels.append(process)
for line in process.stdout:
line=line.strip()
print(line)
match = url_regex.search(line)
if match:
print(f"{Colors.GREEN}[INFO] Public URL detected: {Colors.BOLD}{match.group(0)}{Colors.ENDC}")
except KeyboardInterrupt:
print(f"{Colors.YELLOW}[INFO] CTRL+C detected. Shutting down all tunnels...{Colors.ENDC}")
finally:
terminate_all_tunnels()
print(f"{Colors.GREEN}[INFO] Tunnel stopped.{Colors.ENDC}")
# ---------------- Terminate All Tunnels ----------------
def terminate_all_tunnels():
global running_tunnels
for proc in running_tunnels:
if proc.poll() is None:
try:
os.killpg(os.getpgid(proc.pid), signal.SIGINT)
proc.wait(timeout=5)
except:
proc.kill()
running_tunnels=[]
# ---------------- Main ----------------
def main():
print_banner()
cfg = load_config()
print(f"{Colors.BOLD}Select a tunneling service:{Colors.ENDC}")
for k,c in TUNNEL_CONFIG.items(): print(f"[{Colors.BOLD}{k}{Colors.ENDC}] {c['name']}")
choice = input(f"{Colors.BOLD}Enter choice: {Colors.ENDC}").strip()
if choice not in TUNNEL_CONFIG: print(f"{Colors.RED}[ERROR] Invalid choice{Colors.ENDC}"); return
if not check_cli(choice): return
while True:
try:
port = int(input(f"{Colors.BOLD}Enter port for HTTP server [{cfg.get('port',8000)}]: {Colors.ENDC}") or cfg.get('port',8000))
if 1<=port<=65535: break
except: pass
print(f"{Colors.RED}[ERROR] Invalid port{Colors.ENDC}")
www_path = input(f"{Colors.BOLD}Enter www path [{cfg.get('www_path',str(WWW_DIR))}]: {Colors.ENDC}") or str(WWW_DIR)
os.makedirs(www_path,exist_ok=True)
create_index(www_path)
start_http_server(port,www_path)
# Handle authentication if needed
service_name = TUNNEL_CONFIG[choice]['name']
if TUNNEL_CONFIG[choice]['auth_required']:
token_key = f"{service_name}_token"
token = cfg.get(token_key,"")
if not token:
token = input(f"{Colors.BOLD}Enter {service_name} AuthToken (leave blank to skip): {Colors.ENDC}").strip()
if token and configure_ngrok_token(token):
cfg[token_key] = token
save_config(cfg)
# Run the tunnel
if service_name=="ngrok":
command = f"ngrok http {port}"
elif service_name=="localtunnel (lt)":
command = f"lt --port {port}"
elif service_name=="cloudflared":
command = f"cloudflared tunnel --url http://localhost:{port}"
elif service_name=="Serveo (SSH)":
command = f"ssh -R 80:localhost:{port} serveo.net"
elif service_name=="Pinggy (SSH)":
command = f"ssh -p 443 -R0:127.0.0.1:{port} a.pinggy.io"
elif service_name=="Localxpose (lx)":
command = f"lx tunnel http --port {port}"
else:
command = ""
run_tunnel(command,service_name)
cfg.update({"port":port,"last_choice":choice,"www_path":www_path})
save_config(cfg)
# ---------------- Entry ----------------
if __name__=="__main__":
signal.signal(signal.SIGINT, lambda s,f: terminate_all_tunnels() or sys.exit(0))
main()