File size: 16,531 Bytes
1a9aae2 | 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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | """
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LINUX SYSTEM SERVER โ by BU THE ZYZ STUDIO โ
โ ๐ฅ๏ธ ุณูุฑูุฑ ูุธุงู
ููููุณ โ ููุชุญูู
ููู ุนุจุฑ ุงูุณูุฑูุฑ ุงูุฃูู โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ูุฐุง ุงูู
ูู ุฎุงุต ุจู: ุณูุฑูุฑ 2 (ุณูุฑูุฑ ูุธุงู
Linux)
This file belongs to: SERVER 2 (Linux System Server)
"""
import os
import subprocess
import json
import threading
import time
import shutil
import signal
from pathlib import Path
from flask import Flask, request, jsonify, Response, stream_with_context
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ Security Token โ ุฑู
ุฒ ุงูุฃู
ุงู
# Set as environment variable: LINUX_API_TOKEN
# ุนููู ูุฐุง ุงูู
ุชุบูุฑ ูู ุฅุนุฏุงุฏุงุช Hugging Face Space
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
API_TOKEN = os.environ.get("LINUX_API_TOKEN", "zyz-linux-secret-2025")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ Workspace Directory
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
WORKSPACE = "/workspace"
os.makedirs(WORKSPACE, exist_ok=True)
# Active processes store (for killing long-running processes)
active_processes = {}
process_lock = threading.Lock()
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ Auth Helper
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def verify_token(req) -> bool:
"""ุงูุชุญูู ู
ู ุฑู
ุฒ ุงูุฃู
ุงู ูู ุงูุทูุจ"""
# Check header first
token_header = req.headers.get("X-API-Token", "")
if token_header == API_TOKEN:
return True
# Check JSON body
if req.is_json:
body = req.get_json(silent=True) or {}
if body.get("token", "") == API_TOKEN:
return True
return False
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# โ
Status Endpoint
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@app.route("/")
def root():
return jsonify({
"name": "Linux System Server",
"version": "1.0.0",
"by": "BU THE ZYZ STUDIO",
"status": "online",
"note": "Use /api/status with your token to verify authentication."
})
@app.route("/api/status")
def status():
"""ุญุงูุฉ ุงูุณูุฑูุฑ โ ูุนู
ู ุจุฏูู ุชูุซูู ููุชุญูู ู
ู ุงูุงุชุตุงู"""
try:
uname = subprocess.run("uname -a", shell=True, capture_output=True, text=True, timeout=5)
disk = subprocess.run("df -h /workspace 2>/dev/null || df -h /", shell=True, capture_output=True, text=True, timeout=5)
mem = subprocess.run("free -h", shell=True, capture_output=True, text=True, timeout=5)
python = subprocess.run("python3 --version", shell=True, capture_output=True, text=True, timeout=5)
except Exception:
uname = disk = mem = python = type("R", (), {"stdout": "N/A", "stderr": ""})()
authenticated = verify_token(request)
return jsonify({
"status": "online",
"authenticated": authenticated,
"system": uname.stdout.strip(),
"disk": disk.stdout.strip(),
"memory": mem.stdout.strip(),
"python": python.stdout.strip(),
"workspace": WORKSPACE,
"timestamp": time.time()
})
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# โก Execute Command โ ุชูููุฐ ุฃูุงู
ุฑ ุงูุชุฑู
ููุงู
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@app.route("/api/execute", methods=["POST"])
def execute_command():
"""
ุชูููุฐ ุฃู
ุฑ ุชุฑู
ููุงู ูุงุญุฏ ูุงูุญุตูู ุนูู ุงููุชูุฌุฉ ูุงู
ูุฉ
Execute a single terminal command and get full output
"""
if not verify_token(request):
return jsonify({"error": "Unauthorized โ Invalid or missing API token"}), 401
data = request.get_json(silent=True) or {}
command = data.get("command", "").strip()
cwd = data.get("cwd", WORKSPACE)
timeout = min(int(data.get("timeout", 30)), 300) # max 5 minutes
if not command:
return jsonify({"error": "No command provided"}), 400
# Validate working directory
if not os.path.exists(cwd):
cwd = WORKSPACE
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
cwd=cwd,
timeout=timeout,
env={**os.environ, "HOME": "/root", "TERM": "xterm-256color"}
)
return jsonify({
"success": True,
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode,
"command": command,
"cwd": cwd
})
except subprocess.TimeoutExpired:
return jsonify({
"success": False,
"error": f"Command timed out after {timeout} seconds",
"returncode": -1
}), 408
except Exception as e:
return jsonify({
"success": False,
"error": str(e),
"returncode": -1
}), 500
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ก Stream Execute โ ุชูููุฐ ู
ุน ุจุซ ุงููุชุงุฆุฌ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@app.route("/api/stream", methods=["POST"])
def stream_execute():
"""
ุชูููุฐ ุฃู
ุฑ ู
ุน ุจุซ ุงูู
ุฎุฑุฌุงุช ุณุทุฑุงู ุจุณุทุฑ (ู
ููุฏ ููุฃูุงู
ุฑ ุงูุทูููุฉ)
Stream command output line by line (useful for long-running commands)
"""
if not verify_token(request):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json(silent=True) or {}
command = data.get("command", "").strip()
cwd = data.get("cwd", WORKSPACE)
pid_key = data.get("pid_key", f"proc_{int(time.time())}")
if not command:
return jsonify({"error": "No command provided"}), 400
if not os.path.exists(cwd):
cwd = WORKSPACE
@stream_with_context
def generate():
try:
process = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
cwd=cwd,
env={**os.environ, "HOME": "/root", "TERM": "xterm-256color"},
bufsize=1
)
with process_lock:
active_processes[pid_key] = process
yield f"data: {json.dumps({'type': 'start', 'pid': process.pid, 'command': command})}\n\n"
for line in iter(process.stdout.readline, ""):
yield f"data: {json.dumps({'type': 'output', 'line': line})}\n\n"
process.wait()
with process_lock:
active_processes.pop(pid_key, None)
yield f"data: {json.dumps({'type': 'done', 'returncode': process.returncode})}\n\n"
yield "data: [DONE]\n\n"
except Exception as e:
yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"
return Response(
generate(),
mimetype="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ Kill Process โ ุฅููุงู ุนู
ููุฉ ุฌุงุฑูุฉ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@app.route("/api/kill", methods=["POST"])
def kill_process():
if not verify_token(request):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json(silent=True) or {}
pid_key = data.get("pid_key", "")
with process_lock:
proc = active_processes.get(pid_key)
if proc:
try:
proc.terminate()
time.sleep(0.5)
if proc.poll() is None:
proc.kill()
return jsonify({"success": True, "message": "Process terminated"})
except Exception as e:
return jsonify({"error": str(e)}), 500
return jsonify({"error": "Process not found"}), 404
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ File System Operations
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@app.route("/api/files/list", methods=["GET", "POST"])
def list_files():
"""ูุงุฆู
ุฉ ุงูู
ููุงุช ูู ู
ุณุงุฑ ู
ุนูู"""
if not verify_token(request):
return jsonify({"error": "Unauthorized"}), 401
if request.method == "POST":
data = request.get_json(silent=True) or {}
path = data.get("path", WORKSPACE)
else:
path = request.args.get("path", WORKSPACE)
try:
items = []
for name in sorted(os.listdir(path)):
full = os.path.join(path, name)
try:
stat = os.stat(full)
items.append({
"name": name,
"path": full,
"is_dir": os.path.isdir(full),
"size": stat.st_size,
"modified": stat.st_mtime
})
except Exception:
pass
return jsonify({"success": True, "path": path, "items": items})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/files/read", methods=["POST"])
def read_file():
"""ูุฑุงุกุฉ ู
ุญุชูู ู
ูู"""
if not verify_token(request):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json(silent=True) or {}
path = data.get("path", "").strip()
if not path:
return jsonify({"error": "No path provided"}), 400
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
return jsonify({"success": True, "path": path, "content": content, "size": len(content)})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/files/write", methods=["POST"])
def write_file():
"""ูุชุงุจุฉ ู
ุญุชูู ุฅูู ู
ูู"""
if not verify_token(request):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json(silent=True) or {}
path = data.get("path", "").strip()
content = data.get("content", "")
if not path:
return jsonify({"error": "No path provided"}), 400
try:
dir_ = os.path.dirname(path)
if dir_:
os.makedirs(dir_, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(content)
return jsonify({"success": True, "path": path, "bytes_written": len(content.encode())})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/files/delete", methods=["POST"])
def delete_file():
"""ุญุฐู ู
ูู ุฃู ู
ุฌูุฏ"""
if not verify_token(request):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json(silent=True) or {}
path = data.get("path", "").strip()
if not path:
return jsonify({"error": "No path provided"}), 400
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
return jsonify({"success": True, "deleted": path})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/files/mkdir", methods=["POST"])
def make_dir():
"""ุฅูุดุงุก ู
ุฌูุฏ ุฌุฏูุฏ"""
if not verify_token(request):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json(silent=True) or {}
path = data.get("path", "").strip()
try:
os.makedirs(path, exist_ok=True)
return jsonify({"success": True, "created": path})
except Exception as e:
return jsonify({"error": str(e)}), 500
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ฆ Package Manager โ ุฅุฏุงุฑุฉ ุงูุญุฒู
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@app.route("/api/packages/install", methods=["POST"])
def install_package():
"""ุชุซุจูุช ุญุฒู
ุฉ Python ุฃู apt"""
if not verify_token(request):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json(silent=True) or {}
package = data.get("package", "").strip()
manager = data.get("manager", "pip") # "pip" or "apt"
if not package:
return jsonify({"error": "No package name"}), 400
try:
if manager == "apt":
cmd = f"apt-get install -y {package}"
else:
cmd = f"pip install {package}"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=120)
return jsonify({
"success": result.returncode == 0,
"stdout": result.stdout,
"stderr": result.stderr
})
except subprocess.TimeoutExpired:
return jsonify({"error": "Installation timed out"}), 408
except Exception as e:
return jsonify({"error": str(e)}), 500
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ง System Info โ ู
ุนููู
ุงุช ุงููุธุงู
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@app.route("/api/sysinfo", methods=["GET", "POST"])
def sysinfo():
"""ู
ุนููู
ุงุช ุชูุตูููุฉ ุนู ุงููุธุงู
"""
if not verify_token(request):
return jsonify({"error": "Unauthorized"}), 401
commands = {
"os": "cat /etc/os-release 2>/dev/null | head -5",
"cpu": "lscpu 2>/dev/null | grep -E 'Architecture|CPU\\(s\\)|Model name' | head -5",
"memory": "free -h",
"disk": "df -h",
"network": "ip addr show 2>/dev/null | grep 'inet ' | head -5",
"python": "python3 --version && pip3 list 2>/dev/null | head -20",
"processes":"ps aux --sort=-%cpu 2>/dev/null | head -10",
"uptime": "uptime"
}
info = {}
for key, cmd in commands.items():
try:
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=10)
info[key] = r.stdout.strip()
except Exception:
info[key] = "N/A"
return jsonify({"success": True, "info": info})
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ Run โ ุชุดุบูู ุงูุณูุฑูุฑ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if __name__ == "__main__":
print("=" * 60)
print(" ๐ฅ๏ธ Linux System Server โ BU THE ZYZ STUDIO")
print(" Port: 7860")
print(" Token: Set LINUX_API_TOKEN env variable")
print("=" * 60)
app.run(host="0.0.0.0", port=7860, debug=False, threaded=True)
|