Run Commands With Argument Arrays Not Shell Strings
A command runner that executes binaries with an argument array and no shell, so untrusted values can never be interpreted as shell syntax.
Code
import subprocess
from dataclasses import dataclass
from typing import Mapping, Optional, Sequence
class UnsafeCommandError(ValueError):
"""Raised when a command would require shell interpretation."""
@dataclass(frozen=True)
class CommandResult:
argv: Sequence[str]
returncode: int
stdout: str
stderr: str
def run_command(
binary: str,
args: Sequence[str],
*,
timeout_s: float = 10.0,
env: Optional[Mapping[str, str]] = None,
use_shell: bool = False,
) -> CommandResult:
"""Run binary with an argv list and no shell; return a structured result."""
if use_shell:
raise UnsafeCommandError("shell mode is refused; pass an argv list instead")
if not binary:
raise ValueError("binary must be a non-empty path")
argv = [binary, *[str(a) for a in args]]
try:
completed = subprocess.run(
argv,
shell=False,
capture_output=True,
text=True,
timeout=timeout_s,
env=dict(env) if env is not None else None,
)
except subprocess.TimeoutExpired as exc:
raise TimeoutError("command timed out after %ss" % timeout_s) from exc
except FileNotFoundError as exc:
raise FileNotFoundError("binary not found: %s" % binary) from exc
return CommandResult(
argv=argv,
returncode=completed.returncode,
stdout=completed.stdout,
stderr=completed.stderr,
)Building a command string and passing it to a shell lets a filename containing semicolons or backticks execute arbitrary commands.
Use case: engineers invoking external tools with user influenced arguments
Inputs / outputs
- Input: a binary path, an argument list, optional timeout and environment
- Output: a result object with exit code, stdout and stderr
Error conditions
- shell=True requested (refused)
- timeout exceeded
- binary not found
Approach
use execFile with an argv list and shell disabled; enforce a timeout; capture stdout and stderr as text and return a structured result.
Implementation
import subprocess
from dataclasses import dataclass
from typing import Mapping, Optional, Sequence
class UnsafeCommandError(ValueError):
"""Raised when a command would require shell interpretation."""
@dataclass(frozen=True)
class CommandResult:
argv: Sequence[str]
returncode: int
stdout: str
stderr: str
def run_command(
binary: str,
args: Sequence[str],
*,
timeout_s: float = 10.0,
env: Optional[Mapping[str, str]] = None,
use_shell: bool = False,
) -> CommandResult:
"""Run binary with an argv list and no shell; return a structured result."""
if use_shell:
raise UnsafeCommandError("shell mode is refused; pass an argv list instead")
if not binary:
raise ValueError("binary must be a non-empty path")
argv = [binary, *[str(a) for a in args]]
try:
completed = subprocess.run(
argv,
shell=False,
capture_output=True,
text=True,
timeout=timeout_s,
env=dict(env) if env is not None else None,
)
except subprocess.TimeoutExpired as exc:
raise TimeoutError("command timed out after %ss" % timeout_s) from exc
except FileNotFoundError as exc:
raise FileNotFoundError("binary not found: %s" % binary) from exc
return CommandResult(
argv=argv,
returncode=completed.returncode,
stdout=completed.stdout,
stderr=completed.stderr,
)
Verification tests
import sys
import unittest
from example import UnsafeCommandError, run_command
class CommandRunnerTests(unittest.TestCase):
def test_runs_a_command_without_a_shell(self):
result = run_command(sys.executable, ["-c", "print(2 + 3)"]);
self.assertEqual(result.returncode, 0)
self.assertEqual(result.stdout.strip(), "5")
self.assertFalse(any(";" in a for a in result.argv))
def test_arguments_are_never_shell_interpreted(self):
payload = "safe; rm -rf /"
result = run_command(sys.executable, ["-c", "import sys; print(sys.argv[1])", payload]);
self.assertEqual(result.stdout.strip(), payload)
self.assertEqual(result.returncode, 0)
def test_refuses_shell_mode(self):
with self.assertRaises(UnsafeCommandError):
run_command("echo", ["hi"], use_shell=True)
def test_missing_binary_is_reported(self):
with self.assertRaises(FileNotFoundError):
run_command("definitely-not-a-real-binary-xyz", [])
def test_times_out_a_long_command(self):
with self.assertRaises(TimeoutError):
run_command(sys.executable, ["-c", "import time; time.sleep(5)"], timeout_s=0.3)
if __name__ == "__main__":
unittest.main()
Dependencies and running
No external dependencies (standard library only).
Runtime: python >= 3.9 Entry point: python example.py
Limitations and error handling
no pipeline or redirection support (no shell by design); no streaming output.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.