linum / backend /app.py
Rémy
Add Linux Practice Tool files
f716e02
from flask import Flask, request, jsonify
from flask_cors import CORS
import subprocess
import shlex
app = Flask(__name__)
CORS(app)
ALLOWED_COMMANDS = {
'ls', 'cd', 'pwd', 'echo', 'cat', 'grep', 'find', 'touch', 'mkdir', 'rm', 'cp', 'mv'
}
@app.route('/execute', methods=['POST'])
def execute_command():
command = request.json['command']
try:
# Parse the command to get the base command
base_command = shlex.split(command)[0]
# Check if the base command is allowed
if base_command not in ALLOWED_COMMANDS:
return jsonify({'error': f"Command '{base_command}' is not allowed"}), 403
# Execute the command in a controlled environment
result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=5)
return jsonify({
'output': result.stdout,
'error': result.stderr,
'returncode': result.returncode
})
except subprocess.TimeoutExpired:
return jsonify({'error': 'Command execution timed out'}), 408
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)