CommandRunner

Secure subprocess execution with credential sanitization and platform-aware run-as-user support.

class CommandRunner(logger: MdmLogger | None = None, username: str | None = None, uid: int | None = None)[source]

Bases: object

Safe subprocess execution with logging support.

Parameters:
run(command: str | list[str], timeout: int = 30, env: dict[str, str] | None = None, *, check: bool = True, **kwargs: Any) str | CompletedProcess[str][source]

Run a command and return its output.

  • Pass a list for safety: [“/usr/bin/id”, “-u”, username]

  • Pass a string for shell features: “command | grep something”

When check=True (default), returns stripped stdout as a string and raises on non-zero exit. When check=False, returns the full subprocess.CompletedProcess for caller inspection.

Additional keyword arguments are passed through to subprocess.run (e.g., cwd, input).

Parameters:
  • command (str | list[str]) – Command string or list of arguments

  • timeout (int, optional) – Timeout in seconds, defaults to 30

  • env (dict[str, str] | None, optional) – Environment variables for the subprocess. Replaces the entire environment (same behavior as subprocess.run). None inherits the parent process environment.

  • check (bool, optional) – If True (default), raise CalledProcessError on non-zero exit and return stdout as str. If False, return the CompletedProcess object.

  • kwargs (Any) – Additional keyword arguments passed to subprocess.run

Returns:

Command output (stdout) when check=True, or CompletedProcess when check=False

Return type:

str | subprocess.CompletedProcess[str]

run_as_user(command: list[str], timeout: int = 30, *, check: bool = True, **kwargs: Any) str | CompletedProcess[str][source]

Run a command as the logged in user and return its output.

Uses platform-specific mechanisms: - macOS: launchctl asuser + sudo -u - Windows: PowerShell Start-Process -Credential

Parameters:
  • command (list[str]) – Command string or list of arguments

  • timeout (int, optional) – Timeout in seconds, defaults to 30

  • check (bool, optional) – If True (default), raise CalledProcessError on non-zero exit and return stdout as str. If False, return the CompletedProcess object.

  • kwargs (Any) – Additional keyword arguments passed to subprocess.run

Returns:

Command output (stdout) when check=True, or CompletedProcess when check=False

Return type:

str | subprocess.CompletedProcess[str]