from flask import Flask, render_template, request, jsonify, send_file import subprocess import tempfile import os import shutil import requests app = Flask(__name__) # Temporary directory to store downloaded files TEMP_DIR = tempfile.mkdtemp() @app.route('/') def index(): return render_template('index.html') @app.route('/execute', methods=['POST']) def execute_command(): command = request.json['command'] if command.startswith('pip install'): return execute_pip_install(command) elif command.startswith('git clone'): return execute_git_clone(command) elif command.startswith('python'): return execute_python_script(command) elif command.startswith('download'): return download_file(command) elif command.startswith('!'): return execute_shell_command(command[1:]) else: return jsonify({'output': 'Unknown command. Try pip install, git clone, python, download, or !.'}) def execute_pip_install(command): try: result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True) return jsonify({'output': result.stdout}) except subprocess.CalledProcessError as e: return jsonify({'output': f'Error: {e.stderr}'}) def execute_git_clone(command): try: result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True, cwd=TEMP_DIR) return jsonify({'output': f'Repository cloned successfully to {TEMP_DIR}'}) except subprocess.CalledProcessError as e: return jsonify({'output': f'Error: {e.stderr}'}) def execute_python_script(command): try: with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, dir=TEMP_DIR) as temp_file: temp_file.write(command[7:]) # Remove 'python ' from the beginning temp_file_path = temp_file.name result = subprocess.run(f'python {temp_file_path}', shell=True, check=True, capture_output=True, text=True) os.unlink(temp_file_path) return jsonify({'output': result.stdout}) except subprocess.CalledProcessError as e: return jsonify({'output': f'Error: {e.stderr}'}) def download_file(command): try: _, url = command.split(maxsplit=1) response = requests.get(url) if response.status_code == 200: filename = os.path.join(TEMP_DIR, url.split('/')[-1]) with open(filename, 'wb') as f: f.write(response.content) return jsonify({'output': f'File downloaded successfully: {filename}'}) else: return jsonify({'output': f'Error downloading file: HTTP {response.status_code}'}) except Exception as e: return jsonify({'output': f'Error downloading file: {str(e)}'}) def execute_shell_command(command): try: result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True, cwd=TEMP_DIR) return jsonify({'output': result.stdout}) except subprocess.CalledProcessError as e: return jsonify({'output': f'Error: {e.stderr}'}) @app.teardown_appcontext def cleanup(error): shutil.rmtree(TEMP_DIR, ignore_errors=True) if __name__ == '__main__': app.run(debug=True)