File size: 2,835 Bytes
a15e38b 5bc4351 2c91ea0 382764a a15e38b 21fe3fa 2c91ea0 a15e38b 4d30d4b a15e38b 1917e67 a15e38b 2c91ea0 a15e38b a794cee a15e38b |
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 |
from flask import Flask, request, jsonify, render_template, send_from_directory
import os
import subprocess
import tempfile
import shutil
import sys
app = Flask(__name__)
# Create a temporary directory for operations
temp_dir = tempfile.mkdtemp()
current_dir = temp_dir
def execute_command(command, cwd=None):
"""Executes a command and returns the output."""
process = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=cwd or current_dir
)
stdout, stderr = process.communicate()
return stdout + stderr
@app.route("/")
def index():
return render_template("index.html")
@app.route("/execute", methods=["POST"])
def execute_code():
global current_dir
command = request.json.get("code", "").strip()
if not command:
return jsonify({"result": "Error: No command provided."})
try:
if command.startswith("cd "):
# Change directory
new_dir = os.path.join(current_dir, command[3:])
if os.path.isdir(new_dir):
current_dir = os.path.abspath(new_dir)
return jsonify({"result": f"Changed directory to: {current_dir}"})
else:
return jsonify({"result": f"Error: Directory not found: {new_dir}"})
elif command.startswith("!"):
# Execute shell command
result = execute_command(command[1:])
elif command.startswith("pip install"):
# Install Python package
result = execute_command(f"{sys.executable} -m {command}")
elif command.startswith("git "):
# Execute git command
result = execute_command(command)
else:
# Execute Python code
if command.endswith(".py"):
# Run Python script
result = execute_command(f"{sys.executable} {command}")
else:
# Execute Python code
result = execute_command(f"{sys.executable} -c \"{command}\"")
return jsonify({"result": result})
except Exception as e:
return jsonify({"result": f"Error: {str(e)}"})
@app.route("/cleanup", methods=["POST"])
def cleanup():
global temp_dir, current_dir
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
temp_dir = tempfile.mkdtemp()
current_dir = temp_dir
return jsonify({"result": "Temporary files cleaned up."})
@app.route("/list_files", methods=["GET"])
def list_files():
files = os.listdir(current_dir)
return jsonify({"files": files})
@app.route("/download/<path:filename>", methods=["GET"])
def download_file(filename):
return send_from_directory(current_dir, filename, as_attachment=True)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860) |