Python Security & Automation Cookbook
Curated, production-hardened Python snippets used daily in automation engines and defensive DevSecOps pipelines — zero bloat, standard library first.
import socket, ssl
from datetime import datetime
def cert_days_left(host: str, port: int = 443) -> int:
ctx = ssl.create_default_context()
with socket.create_connection((host, port), timeout=5) as sock:
with ctx.wrap_socket(sock, server_hostname=host) as ssock:
cert = ssock.getpeercert()
exp = datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
return (exp - datetime.utcnow()).days
print(cert_days_left("example.com"))import asyncio
async def check_port(host: str, port: int, timeout: float = 1.5) -> tuple[int, bool]:
try:
_, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout)
writer.close()
await writer.wait_closed()
return port, True
except OSError:
return port, False
async def main():
results = await asyncio.gather(*(check_port("127.0.0.1", p) for p in [22, 80, 443, 3000]))
print([p for p, ok in results if ok])
asyncio.run(main())import hashlib
from pathlib import Path
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
print(sha256_file(Path("artifact.tar.gz")))import subprocess
def run_safe(cmd: list[str], timeout: int = 30) -> str:
# Always pass list[str] with shell=False to prevent command injection
res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=True)
return res.stdout.strip()
print(run_safe(["git", "rev-parse", "--short", "HEAD"]))import json, logging, sys
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
return json.dumps({
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
"time": self.formatTime(record),
})
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=logging.INFO, handlers=[handler])
logging.info("Worker initialized")import asyncio, random
async def retry_async(fn, retries: int = 4, base: float = 0.5):
for attempt in range(retries):
try:
return await fn()
except Exception:
if attempt == retries - 1:
raise
await asyncio.sleep(base * (2 ** attempt) + random.uniform(0, 0.25))Practical Scenarios
When & Why to Use Python Security & Automation Cookbook
Eliminating Command Injection Risks
Use the safe subprocess list-argument pattern (shell=False) instead of vulnerable os.system() or string interpolation.
Building Monitoring & Health Scripts
Drop in TLS certificate expiry monitoring, async port reachability probes, and file SHA-256 verification.
Production Worker Observability
Copy structured JSON logging and exponential-backoff async retry helpers directly into FastAPI or worker repos.
Related Tools
Browse all toolscURL → Python httpx & requests
Convert any cURL command into clean async httpx or synchronous requests Python code with headers and JSON payloads.
JSON → Pydantic / Dataclass Generator
Paste any JSON API response to generate nested Pydantic v2 BaseModel, @dataclass, or TypedDict schemas automatically.
Authorized Audit & Recon Commands
Parameterized defensive commands for curl header inspection, openssl TLS verification, nmap, dig DNS/DMARC, ss, and secret scanning.