File size: 1,729 Bytes
4d30d4b
5bc4351
382764a
 
 
21fe3fa
 
 
5bc4351
382764a
 
4d30d4b
 
 
 
 
 
5bc4351
 
382764a
21fe3fa
5bc4351
 
 
 
 
 
 
 
 
 
 
 
 
 
382764a
5bc4351
 
 
 
 
 
 
 
 
21fe3fa
5bc4351
21fe3fa
5bc4351
21fe3fa
382764a
 
5bc4351
382764a
 
 
5bc4351
382764a
 
4d30d4b
 
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
from flask import Flask, request, jsonify, render_template
import os
import subprocess
import tempfile
import shutil

app = Flask(__name__)

# Create a temporary directory for operations
temp_dir = tempfile.mkdtemp()

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/execute", methods=["POST"])
def execute_code():
    command = request.json.get("code", "").strip()
    response = ""

    try:
        # Ensure all operations happen within the temporary directory
        os.chdir(temp_dir)

        if command.startswith("!"):
            # Handle shell commands (e.g., git clone, cd, pip install)
            shell_command = command[1:]
            process = subprocess.run(
                shell_command,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
            )
            response = process.stdout + process.stderr
        else:
            # Handle Python code execution
            process = subprocess.run(
                ["python3", "-c", command],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
            )
            response = process.stdout + process.stderr

    except Exception as e:
        response = f"Error: {e}"

    return jsonify({"result": response})

@app.route("/cleanup", methods=["POST"])
def cleanup():
    # Clean up the temporary directory and recreate it
    global temp_dir
    if os.path.exists(temp_dir):
        shutil.rmtree(temp_dir)
        temp_dir = tempfile.mkdtemp()
    return jsonify({"result": "Temporary files cleaned up."})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)