File size: 2,068 Bytes
fbf3c28 |
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 |
"""
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
|