Security Automation with Python & Scripting
Developing custom security tooling: socket probes, HTTP verification scripts, regex log parsers, and CLI interfaces.
Overview
Security Automation with Python bridges the gap between manual command execution and automated security workflows. Developing lightweight, targeted Python utilities enables security practitioners to automate port verification, inspect HTTP headers at scale, extract security indicators from logs using regular expressions, and build automated triage pipelines.
Core Concepts
- Socket Programming: Utilizing the Python
socketlibrary to perform raw TCP connection handshakes and probe service availability without external dependencies. - HTTP Telemetry Verification: Using the
requestsmodule to audit HTTP status codes, detect missing security headers (e.g. HSTS, CSP), and trace redirection chains. - Regex Telemetry Parsing: Applying the
reengine to extract IP addresses, CVE identifiers, and anomalous log records from large system log streams. - CLI Script Packaging: Building user-friendly command-line tools using Python's standard
argparsemodule.
Tools & Requirements
Python 3.10+, pip, and the requests package.
$ python3 --version $ pip install requests
Commands & Practical Examples
1. Lightweight TCP Port Probe (Pure Standard Library)
A simple, zero-dependency Python script to verify if a port is open on a target host:
import socket
def check_port(host, port, timeout=2.0):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
try:
s.connect((host, port))
s.close()
return True
except (socket.timeout, ConnectionRefusedError):
return False
for p in [22, 80, 443, 8080]:
status = "OPEN" if check_port("192.168.1.10", p) else "CLOSED"
print(f"Port {p}: {status}")
2. HTTP Security Header Inspector
Verify security response headers (Content-Security-Policy, HSTS, X-Frame-Options) across a web application:
import requests
url = "http://192.168.1.10"
resp = requests.get(url, timeout=5)
required_headers = [
"Content-Security-Policy",
"Strict-Transport-Security",
"X-Frame-Options",
"X-Content-Type-Options"
]
print(f"Auditing security headers for: {url}")
for h in required_headers:
present = h in resp.headers
print(f" [{'โ' if present else 'โ'}] {h}: {resp.headers.get(h, 'MISSING')}")
3. Extracting CVE IDs and IPv4 Addresses from Text Logs
Extract indicators of compromise using regular expressions:
import re
log_data = "Advisory CVE-2021-41773 reported from 192.168.1.50 attacking 10.0.0.1"
ips = re.findall(r'(?:\d{1,3}\.){3}\d{1,3}', log_data)
cves = re.findall(r'CVE-\d{4}-\d{4,7}', log_data)
print("IPs Found:", ips)
print("CVEs Found:", cves)
Practical Workflow
- Define Task: Identify repetitive validation task (e.g. checking 50 hosts for an open management port).
- Select Libraries: Choose standard library modules (
socket,re,argparse) where possible to avoid dependency friction. - Add Timeouts: Always configure explicit network timeouts (
timeout=3.0) to prevent scripts from hanging indefinitely. - Validate Locally: Test against local lab targets before applying to large scopes.
Common Mistakes & Troubleshooting
- Missing Timeout Configuration: Socket operations default to blocking mode. An unreachable host will stall execution indefinitely if timeout is not specified.
- Unbounded Threading: Spawning thousands of unthrottled worker threads causes local socket exhaustion. Use
concurrent.futures.ThreadPoolExecutor(max_workers=20).
Security Considerations & Scoping
Automated scripts execute significantly faster than manual commands. Ensure custom automation tools incorporate rate limiting to prevent inadvertent denial of service in laboratory environments.
Related Topics
- Module 13: AI & Agentic Workflows in Cybersecurity
- Module 11: Linux System Security & Defensive Hardening
- Module 14: Security Tools Command Index
Further Reading & TryHackMe Paths
- TryHackMe Rooms: Python Basics, Python for Cyber Security.
- Project Source: Inspired by automation implementations in SentinelAI and CyberAI.