Skip to main content

9.1 Python for Cyber Security

Python is widely used in cyber security for automation, analysis, network inspection, and secure tooling. This section uses official Python docs plus official OWASP/NIST references for security concepts.

Security-focused Python capabilities

  • Fast scripting for incident response tasks
  • Log and artifact parsing using stdlib modules
  • Socket-level networking for protocol inspection
  • Cryptographic and security primitives from standard modules
  • Subprocess and OS integration for controlled automation

Useful standard library modules

  • hashlib, hmac, secrets: hashing, message authentication, secure token generation
  • ssl: TLS support and certificate verification controls
  • socket: low-level TCP/UDP communication
  • ipaddress: safe IPv4/IPv6 parsing and network logic
  • subprocess: controlled process invocation
  • logging: auditable structured logs

Secure coding essentials

  • Validate and sanitize all untrusted input
  • Avoid eval()/exec() on user-provided data
  • Use parameterized database queries (or ORM)
  • Keep secrets in environment/secret managers, not source files
  • Prefer explicit allow-lists over deny-lists
  • Apply least privilege for files, processes, and service accounts

Practical mini examples

Generate secure token

import secrets

token = secrets.token_urlsafe(32)

SHA-256 hash

import hashlib

digest = hashlib.sha256(b"payload").hexdigest()

Safe subnet validation

import ipaddress

net = ipaddress.ip_network("10.10.0.0/16")
print(ipaddress.ip_address("10.10.4.8") in net)

Official references