| """ | |
| id: run_script | |
| title: Run Shell Script (unsafe) | |
| author: admin | |
| description: Run a multi-line bash script with optional working directory and env. | |
| version: 0.1.0 | |
| license: Proprietary | |
| """ | |
| import subprocess | |
| import tempfile | |
| import os | |
| from typing import Optional, Dict | |
| class Tools: | |
| def __init__(self): | |
| pass | |
| def run( | |
| self, | |
| script: str, | |
| cwd: Optional[str] = None, | |
| env: Optional[Dict[str, str]] = None, | |
| ) -> dict: | |
| """ | |
| Execute a multi-line shell script via bash -lc. | |
| :param script: The full bash script contents. | |
| :param cwd: Working directory to run in (optional). | |
| :param env: Environment overrides {key: value} (optional). | |
| :return: {"stdout": str, "stderr": str, "exit_code": int} | |
| """ | |
| d = os.environ.copy() | |
| if isinstance(env, dict): | |
| for k, v in env.items(): | |
| if isinstance(k, str) and isinstance(v, str): | |
| d[k] = v | |
| try: | |
| with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as f: | |
| f.write("#!/usr/bin/env bash\nset -euo pipefail\n") | |
| f.write(script) | |
| path = f.name | |
| os.chmod(path, 0o700) | |
| p = subprocess.run( | |
| ["bash", "-lc", path], | |
| capture_output=True, | |
| text=True, | |
| cwd=cwd or None, | |
| env=d, | |
| timeout=300, | |
| ) | |
| return {"stdout": p.stdout, "stderr": p.stderr, "exit_code": p.returncode} | |
| except subprocess.TimeoutExpired as e: | |
| return { | |
| "stdout": e.stdout or "", | |
| "stderr": (e.stderr or "") + "\n[timeout]", | |
| "exit_code": 124, | |
| } | |
| except Exception as e: | |
| return {"stdout": "", "stderr": str(e), "exit_code": 1} | |
| finally: | |
| try: | |
| if "path" in locals() and os.path.exists(path): | |
| os.remove(path) | |
| except Exception: | |
| pass | |