| from flask import Flask, render_template, request, jsonify |
| import subprocess |
| import os |
|
|
| app = Flask(__name__) |
|
|
| session_state = {"cwd": "/", "env": os.environ.copy()} |
|
|
|
|
| def execute_command(cmd, state): |
| if not cmd.strip(): |
| return [] |
|
|
| if cmd.strip() == "exit": |
| return ["logout"] |
|
|
| try: |
| if cmd.startswith("cd "): |
| path = cmd[3:].strip().strip("'\"") |
| if path == "": |
| path = state["env"].get("HOME", "/") |
| elif path == "~": |
| path = state["env"].get("HOME", "/") |
| elif not path.startswith("/"): |
| path = os.path.join(state["cwd"], path) |
|
|
| if os.path.isdir(path): |
| state["cwd"] = os.path.realpath(path) |
| return [] |
| else: |
| return [f"cd: {cmd[3:].strip()}: No such file or directory"] |
|
|
| result = subprocess.run( |
| cmd, |
| shell=True, |
| cwd=state["cwd"], |
| capture_output=True, |
| text=True, |
| timeout=10, |
| env=state["env"], |
| ) |
|
|
| output = result.stdout |
| if result.stderr: |
| output += result.stderr |
|
|
| if not output: |
| return [] |
|
|
| return output.rstrip("\n").split("\n") |
|
|
| except subprocess.TimeoutExpired: |
| return ["Command timed out"] |
| except Exception as e: |
| return [f"{cmd}: {str(e)}"] |
|
|
|
|
| @app.route("/") |
| def index(): |
| return render_template("index.html") |
|
|
|
|
| @app.route("/execute", methods=["POST"]) |
| def execute(): |
| data = request.json |
| cmd = data.get("command", "") |
|
|
| output = execute_command(cmd, session_state) |
|
|
| return jsonify({"output": output, "command": cmd}) |
|
|
|
|
| @app.route("/reset", methods=["POST"]) |
| def reset(): |
| session_state["cwd"] = session_state["env"].get("HOME", "/") |
| return jsonify({"status": "reset"}) |
|
|
|
|
| if __name__ == "__main__": |
| app.run(host="0.0.0.0", port=7860) |
|
|