File size: 1,014 Bytes
0e02b97
 
ecc9e42
7bd7366
ecc9e42
 
7bd7366
 
ecc9e42
 
7bd7366
ecc9e42
 
 
 
7bd7366
ecc9e42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

__all__ = ["execute_terminal"]

import subprocess
from typing import Final


def execute_terminal(command: str, *, timeout: int = 30) -> str:
    """Execute a shell command inside an isolated Linux VM.

    The command is executed with network access enabled. Output from both
    ``stdout`` and ``stderr`` is captured and returned. Commands are killed if
    they exceed ``timeout`` seconds.
    """
    try:
        completed = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            timeout=timeout,
        )
    except subprocess.TimeoutExpired as exc:
        return f"Command timed out after {timeout}s: {exc.cmd}"
    except Exception as exc:  # pragma: no cover - unforeseen errors
        return f"Failed to execute command: {exc}"

    output = completed.stdout
    if completed.stderr:
        output = f"{output}\n{completed.stderr}" if output else completed.stderr
    return output.strip()