|
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) |
|
|
|
|
|
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) |
|
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, |
|
) |
|
|
|
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: |
|
|
|
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) |
|
|