-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.py
More file actions
79 lines (70 loc) · 2.55 KB
/
Copy pathserver.py
File metadata and controls
79 lines (70 loc) · 2.55 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
import os
import socket
import subprocess
import sys
import shutil
def get_free_port(start=5500, max_tries=50):
port = start
while port < start + max_tries:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind(('0.0.0.0', port))
return port
except OSError:
port += 1
raise OSError("No free ports found.")
def get_local_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
except Exception:
ip = "localhost"
return ip
def is_python_installed():
return shutil.which("python") or shutil.which("python3")
def offer_install_python_linux():
print("Python not found. Attempting installation (Linux only)...")
confirm = input("Install Python via apt? [Y/n]: ").strip().lower()
if confirm in ("y", ""):
subprocess.call(["sudo", "apt", "update"])
subprocess.call(["sudo", "apt", "install", "-y", "python3"])
else:
print("Python is required. Exiting.")
sys.exit(1)
def launch_server_in_terminal(port):
script = f"""
import http.server
import socketserver
PORT = {port}
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(('0.0.0.0', PORT), Handler) as httpd:
print('Serving at: http://localhost:' + str(PORT))
print('Serving on LAN: http://{get_local_ip()}:' + str(PORT))
httpd.serve_forever()
"""
filename = "temp_server.py"
with open(filename, "w") as f:
f.write(script)
if os.name == "nt": # Windows
terminal = "powershell" if shutil.which("powershell") else "cmd"
subprocess.Popen([terminal, "/c", f"python {filename}"], creationflags=subprocess.CREATE_NEW_CONSOLE)
else: # Linux
terminals = ["gnome-terminal", "x-terminal-emulator", "konsole", "xterm"]
for term in terminals:
if shutil.which(term):
subprocess.Popen([term, "-e", f"python3 {filename}"])
break
else:
print("No compatible Linux terminal found. Run the server manually: python3 temp_server.py")
if __name__ == "__main__":
if not is_python_installed():
if os.name == "nt":
print("Python is not installed. Please install Python from https://python.org before running this script.")
sys.exit(1)
else:
offer_install_python_linux()
port = get_free_port()
print(f"Launching server on port {port}...")
launch_server_in_terminal(port)