| 191 | @app.route('/execute', methods=['POST']) |
| 192 | @app.route('/setup/execute', methods=['POST']) |
| 193 | def execute_command(): |
| 194 | data = request.json |
| 195 | # The 'command' key in the JSON request should contain the command to be executed. |
| 196 | shell = data.get('shell', False) |
| 197 | command = data.get('command', "" if shell else []) |
| 198 | timeout = data.get('timeout', 120) |
| 199 | |
| 200 | if isinstance(command, str) and not shell: |
| 201 | command = shlex.split(command) |
| 202 | |
| 203 | # Expand user directory |
| 204 | if isinstance(command, list): |
| 205 | for i, arg in enumerate(command): |
| 206 | if arg.startswith("~/"): |
| 207 | command[i] = os.path.expanduser(arg) |
| 208 | |
| 209 | try: |
| 210 | if platform_name == "Windows": |
| 211 | result = subprocess.run( |
| 212 | command, |
| 213 | stdout=subprocess.PIPE, |
| 214 | stderr=subprocess.PIPE, |
| 215 | shell=shell, |
| 216 | text=True, |
| 217 | timeout=timeout, |
| 218 | creationflags=subprocess.CREATE_NO_WINDOW, |
| 219 | ) |
| 220 | else: |
| 221 | result = subprocess.run( |
| 222 | command, |
| 223 | stdout=subprocess.PIPE, |
| 224 | stderr=subprocess.PIPE, |
| 225 | shell=shell, |
| 226 | text=True, |
| 227 | timeout=timeout, |
| 228 | ) |
| 229 | |
| 230 | return jsonify({ |
| 231 | 'status': 'success', |
| 232 | 'output': result.stdout, |
| 233 | 'error': result.stderr, |
| 234 | 'returncode': result.returncode |
| 235 | }) |
| 236 | except subprocess.TimeoutExpired: |
| 237 | return jsonify({ |
| 238 | 'status': 'error', |
| 239 | 'message': f'Command timeout after {timeout} seconds' |
| 240 | }), 408 |
| 241 | except Exception as e: |
| 242 | return jsonify({ |
| 243 | 'status': 'error', |
| 244 | 'message': str(e) |
| 245 | }), 500 |
| 246 | |
| 247 | @app.route('/execute_with_verification', methods=['POST']) |
| 248 | @app.route('/setup/execute_with_verification', methods=['POST']) |