#Why this matters
Security analysts and CTF players regularly face repetitive data problems: verifying SHA-256 digests across thousands of downloaded artifacts, peeling nested Base64 or hex encodings off log fields, or combining regex extraction from an earlier lesson with an HTTP lookup. Throwaway one-liners break on unexpected characters and leave no record of what ran. Turning those steps into a small, composable argparse pipeline makes your work fast, auditable, and reusable.
#Designing clean CLI scripts with argparse
Hardcoding file paths inside a script forces you to edit source code on every run. Instead, separate your core functions from CLI flag parsing with argparse.ArgumentParser and pathlib.Path:
import argparse
import sys
from pathlib import Path
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Verify SHA-256 digests for artifacts in a directory."
)
parser.add_argument("--input", type=Path, required=True, help="Artifact file or folder")
parser.add_argument("--target", required=True, help="Expected 64-char SHA-256 hex digest")
parser.add_argument("--json", action="store_true", help="Emit JSON output")
return parser.parse_args(argv)Returning clear exit codes (0 on success, 1 on mismatch or missing file, 2 on invalid CLI arguments from argparse) lets bash loops, CI checks, and incident playbooks chain your script reliably.
#Streaming decode and hash pipelines
A robust parsing pipeline treats each stage as a small, testable transformation:
- Read streampathlib / line or 64 KB chunks
- Decode / Parsebase64 or regex with error handling
- Hash & Matchhashlib.sha256 comparison
- EmitStructured JSON or CSV record
Never call .read() on an unknown artifact that could be gigabytes large, and never silently accept corrupted Base64 input. Use base64.b64decode(line, validate=True) inside try/except binascii.Error so malformed lines are counted and skipped cleanly. For integrity verification, always use hashlib.sha256() (MD5 and SHA-1 are deprecated for security verification due to collision attacks, and only appear when inspecting legacy forensic records).
import base64
import binascii
import hashlib
import json
from pathlib import Path
def sha256_file(path: Path, chunk_size: int = 65536) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
while chunk := f.read(chunk_size):
h.update(chunk)
return h.hexdigest()
def find_b64_match(candidates_path: Path, target_hex: str) -> dict:
target = target_hex.strip().lower()
skipped = 0
with candidates_path.open("r", encoding="utf-8", errors="replace") as f:
for line_no, raw in enumerate(f, start=1):
token = raw.strip()
if not token:
continue
try:
decoded = base64.b64decode(token, validate=True)
except binascii.Error:
skipped += 1
continue
digest = hashlib.sha256(decoded).hexdigest()
if digest == target:
return {"matched": True, "line": line_no, "sha256": digest, "skipped": skipped}
return {"matched": False, "skipped": skipped}Emitting json.dumps(result) to stdout lets tools like jq or a SIEM ingest script consume the outcome directly without brittle string splitting.
#Safe subprocess orchestration
Sometimes a pipeline needs an external CLI tool such as tshark or openssl to inspect a binary container. Passing a shell command string with shell=True allows filenames containing ;, $(), or backticks to execute arbitrary OS commands. Always pass an explicit argument list with shell=False (the default):
| Option | Safe pattern | Why it matters |
|---|---|---|
| Command argument | ["openssl", "x509", "-in", str(cert_path)] |
Bypasses shell metacharacter parsing |
shell flag |
shell=False (default) |
Prevents command injection from filenames |
timeout |
timeout=30 |
Stops hung child tools from blocking pipelines |
check |
check=True |
Raises CalledProcessError on non-zero exit |
capture_output |
capture_output=True, text=True |
Captures stdout and stderr cleanly for logging |
#Defending and common mistakes
When writing automation that processes untrusted files or logs, treat filenames, archive paths, and decoded strings as hostile data:
- Never use
shell=Truewith file paths or extracted strings insubprocess.run(). - Avoid loading whole files into RAM with
.read()before hashing; stream in 64 KB chunks. - Pass
validate=Truetobase64.b64decode(), because default decoding silently ignores non-alphabet characters and can mask corrupted or padded inputs. - Avoid
eval()orpickle.loads()on untrusted input files; parse structured artifacts withjson.loads()orcsv.DictReader(). - Do not rely on MD5 or SHA-1 when verifying software or artifact integrity; standardise on SHA-256.
#Summary
- Use
argparse,pathlib.Path, and meaningful exit codes to turn ad-hoc scripts into reusable CLI tools. - Stream files and line lists in chunks with
hashlib.sha256()andbase64.b64decode(..., validate=True)so large or malformed inputs do not crash your pipeline. - Output structured JSON or CSV records for reliable downstream filtering and audit trails.
- Call external tools through
subprocess.run([...], timeout=..., check=True)withshell=Falseto prevent command injection.