File size: 1,206 Bytes
f716e02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)