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
| from flask import Flask, jsonify, request from functools import wraps import uuid import subprocess import pexpect
app = Flask(__name__)
def require_key(f): @wraps(f) def decorated_function(*args, **kwargs): print(request.headers) key = request.headers.get('X-API-KEY') print(keys) if key not in keys: return jsonify({'error': 'Invalid API key'}), 401 return f(*args, **kwargs) return decorated_function
@app.route('/key', methods=['GET']) def create_key(): key = str(uuid.uuid4()) keys[key] = True print(keys) return jsonify({'key': key})
@app.route('/command', methods=['GET']) @require_key def get_functions(): try: result = subprocess.run(['ls', '/server/bin'], capture_output=True, text=True) commands = result.stdout.split('\n') return jsonify({'status': 'success', 'commands': commands}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)})
@app.route('/execute', methods=['POST']) @require_key def execute(): """ 执行传入的命令并返回结果 """ data = request.json print(data) commands = data.get('commands') result = [] if not commands: return jsonify({'status': 'error', 'message': 'No command provided'}) try: shell = pexpect.spawn('/bin/bash') for command in commands: if not isinstance(command, dict): return jsonify({'status': 'error','message': 'Invalid command format'}) command_line = [] command_line.append(command["command"]) command_line.extend(command["args"]) cmd = " ".join(command_line) marker = f"CMD_END_{hash(cmd)}" shell.sendline(f"{cmd}; echo '{marker}'") shell.expect(marker) output = shell.before.decode().strip() print(output) result.append( { 'command': cmd, 'status':'success', 'stdout': output, }) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) shell.close() print(result) return jsonify({"result": result})
if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)
|