Lesson 2 of 9 · 24m
Safe Execution Primitives: Subprocesses, HTTP, Files, and Secrets
The boring primitives are where automation gets dangerous; command execution, HTTP clients, filesystem writes, and credential handling need deliberate guardrails.
Security automation touches powerful interfaces: shell commands, cloud APIs, ticket systems, scanners, firewalls, and production credentials. Most automation incidents are not exotic; they are concatenated shell commands, missing timeouts, or retries that hammered an API into an outage.
Subprocess is a tool, not a template language
Use subprocess.run with an argument list. Do not use shell=True unless you can explain exactly why the shell is required.
import subprocess
result = subprocess.run(
["nmap", "-sV", "-oX", "-", target],
check=True, capture_output=True, text=True, timeout=120,
)
xml_output = result.stdoutAn argument list keeps spaces and metacharacters inside one argument. shell=True reintroduces quoting rules, variable expansion, and command injection. Validate user-controlled input before it reaches a command: IP addresses with ipaddress.ip_address, domains against a strict allowlist, never free text as a command fragment.
HTTP clients need deadlines and identity
The default HTTP example is operationally unacceptable: no timeout, no retry policy, no user agent, and no model of status codes. Build one client wrapper and use it everywhere.
import httpx
client = httpx.Client(
base_url="https://scanner.sudosecurity.org",
timeout=httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0),
headers={"User-Agent": "secops-automation/1.4 (+security@sudosecurity.org)"},
)
response = client.get("/api/scans", params={"status": "finished", "limit": 100})
response.raise_for_status()Put authentication in the same wrapper. Do not paste tokens into per-script headers where they end up in logs, screenshots, and shell history; read them from the environment or a secret manager and fail loudly when absent.
Filesystem writes are transactions in spirit
A half-written report looks exactly like a complete report until someone uses it. Write to a temporary file in the same directory, flush it, then atomically rename.
import os, tempfile
from pathlib import Path
def atomic_write(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".")
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(content)
os.replace(tmp, path)Use explicit encodings and restrictive permissions for sensitive artifacts. os.chmod(path, 0o600) is often more important than the report format.
Field notes
- Every external call needs a timeout; infinite hangs are invisible queue blockage.
- Capture stderr from tools — security products often put the only useful diagnostic there while exiting zero.
- Do not log full URLs when credentials can appear in query strings.
- Treat tool output as untrusted input even when you generated the command yourself.
Was this lesson helpful?