Python · Cheat sheet
Python for DevSecOps cheat sheet
Python for DevSecOps cheat sheet: venvs, dependency locking, stdlib one-liners, SAST scanners, and testing.
Run & REPL
Beginnerpython3 script.py- Run a script.
python3 -c "print(1+1)"- Run a one-liner inline.Example output
2
python3 -m http.server 8080 --bind 127.0.0.1- Serve this directory on localhost only (default binds all interfaces).Example output
Serving HTTP on 127.0.0.1 port 8080 (http://127.0.0.1:8080/) ...
python3 -m json.tool file.json- Validate and pretty-print JSON.
python3 -i script.py- Run, then drop into the REPL with state intact.
python3 --version- Check the interpreter version.
venv & packages
Beginnerpython3 -m venv .venv- Create an isolated environment.
source .venv/bin/activate- Activate it (prompt shows the venv).Example output
(.venv) $
pip install requests- Install a package into the venv.
pip install -r requirements.txt- Install a project’s pinned deps.
pip freeze > requirements.txt- Snapshot exact installed versions.
pip list --outdated- Show packages with newer releases.
pipx install <tool>- Install a CLI tool in its own isolated env.
uv venv && uv pip sync --require-hashes requirements.txt- Install exactly the locked, hash-checked set; packages not in the file are removed.
Dependency locking
Intermediatepip-compile requirements.in- Resolve a fully pinned lock file (pip-tools).
uv pip compile --generate-hashes requirements.in -o requirements.txt- Same hash-pinned lock with uv (Astral), a faster pip-tools replacement.
pip-compile --generate-hashes requirements.in- Lock with sha256 hashes so pip --require-hashes can verify.
pip-sync requirements.txt- Make the venv match the lock exactly.
pip install --require-hashes -r requirements.txt- Refuse deps that fail hash checks (supply-chain).
poetry add requests / poetry install- Add + install with Poetry’s lockfile.
Handy stdlib
Intermediatesubprocess.run(["ls"], capture_output=True, text=True)- Shell out and capture stdout/stderr safely.
shlex.quote(user_value)- Only when a shell is unavoidable: quote each untrusted argument (argv lists need no quoting).
tarfile.open(p).extractall(dest, filter="data")- Strips leading slashes, then refuses members outside dest, links to absolute or outside paths, and device files; default since 3.14.
from pathlib import Path; Path("/etc").glob("*.conf")- Modern filesystem paths and globbing.
import argparse- Build a real CLI with flags and help.
logging.basicConfig(level=logging.INFO)- Structured logging instead of print.
from datetime import datetime, timezone; datetime.now(timezone.utc)- Aware UTC timestamp (datetime.utcnow() is deprecated since 3.12).
os.environ.get("TOKEN")- Read config/secrets from the environment.
yaml.safe_load(Path("cfg.yaml").read_text())- PyYAML: parse untrusted YAML without building arbitrary objects.
python3 -c "import secrets; print(secrets.token_hex(16))"- Generate a cryptographically strong token.Example output
b1946ac92492d2347c6235b4d2611184
Security scanners
Advancedbandit -r .- Find insecure code patterns (SAST for Python).Example output
>> Issue: [B602:subprocess_popen_with_shell_equals_true] Severity: High
bandit -r src --severity-level medium- Report only medium and high severity findings (a sensible CI gate).
pip-audit- Report known CVEs in installed dependencies.Example output
Found 2 known vulnerabilities in 1 package
pip-audit -r requirements.txt --require-hashes- Audit a hash-pinned requirements file; exits non-zero on known vulnerabilities.
safety scan- Alternative dependency scan; replaces deprecated safety check (needs login).
detect-secrets scan > .secrets.baseline- Catch hardcoded secrets in the repo.
semgrep --config auto .- Run Registry rules picked for the project (sends the project URL to Semgrep).
Crypto & hashing
Advancedpython3 -c "import hashlib;print(hashlib.sha256(b'x').hexdigest())"- Hash bytes with SHA-256.Example output
2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881
hashlib.file_digest(f, "sha256").hexdigest()- Checksum an open binary file without reading it all into memory (3.11+).
requests.get(url, timeout=10)- TLS is verified by default; always set a timeout and never pass verify=False.
ssl.create_default_context()- Hostname and chain checks on; 3.13+ also enables VERIFY_X509_STRICT.
secrets.compare_digest(a, b)- Constant-time compare (avoid timing attacks).
import hmac; hmac.new(key, msg, "sha256").hexdigest()- Sign a message with an HMAC.
from cryptography.fernet import Fernet- Authenticated symmetric encryption made simple.
Lint, type & test
Advancedruff check .- Extremely fast linter (flake8/isort replacement).
black .- Opinionated auto-formatter.
mypy src/- Static type-check annotated code.
pytest -q- Run the test suite quietly.Example output
12 passed in 0.34s
pytest --cov=src- Report test coverage.
Related
- Cheat sheetLinux command cheat sheet
- Cheat sheetBash scripting cheat sheet
- Interview guideLinux interview questions
- Interview guideDevSecOps & supply-chain security interview questions
- CoursePython for security automation
- CourseLinux essentials
- CourseLinux hardening
- Field noteSAST in CI with Semgrep and custom rules
- Field noteCI dependency scanning: pip-audit, npm audit, fail fast
- Field noteParse auditd logs with Python before they hit your SIEM
Primary references
Found a technical issue on this page? Report it with the tool version you used and the behavior you saw. How resources are maintained.
Go deeper
Hands-on courses for Python