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

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

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

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

@socketio.on("execute")
def execute_command(data):
    command = data.get("code", "").strip()
    response = ""

    try:
        os.chdir(temp_dir)  # Ensure all operations happen within the temporary directory
        emit("output", {"data": f"$ {command}\n"}, broadcast=True)

        if command.startswith("!"):
            shell_command = command[1:]
            process = subprocess.Popen(
                shell_command,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
            )
            # Stream output live
            for line in process.stdout:
                emit("output", {"data": line}, broadcast=True)
            for line in process.stderr:
                emit("output", {"data": line}, broadcast=True)

            process.wait()
            emit("output", {"data": "Command execution complete.\n"}, broadcast=True)
        else:
            # Handle Python script execution
            process = subprocess.Popen(
                ["python3", "-c", command],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
            )
            for line in process.stdout:
                emit("output", {"data": line}, broadcast=True)
            for line in process.stderr:
                emit("output", {"data": line}, broadcast=True)
            process.wait()
            emit("output", {"data": "Python execution complete.\n"}, broadcast=True)
    except Exception as e:
        emit("output", {"data": f"Error: {e}\n"}, broadcast=True)

@socketio.on("cleanup")
def cleanup():
    global temp_dir
    if os.path.exists(temp_dir):
        shutil.rmtree(temp_dir)
        temp_dir = tempfile.mkdtemp()
    emit("output", {"data": "Temporary files cleaned up.\n"}, broadcast=True)

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