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 generationssl: TLS support and certificate verification controlssocket: low-level TCP/UDP communicationipaddress: safe IPv4/IPv6 parsing and network logicsubprocess: controlled process invocationlogging: 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
- Python
secrets: https://docs.python.org/3/library/secrets.html - Python
hashlib: https://docs.python.org/3/library/hashlib.html - Python
ssl: https://docs.python.org/3/library/ssl.html - Python
socket: https://docs.python.org/3/library/socket.html - Python security considerations: https://docs.python.org/3/library/security_warnings.html
- OWASP Top 10: https://owasp.org/www-project-top-ten/
- NIST Cybersecurity Framework: https://www.nist.gov/cyberframework