01 — Python for Cybersecurity
Python is one of the most useful programming languages for cybersecurity professionals because it combines:
SIMPLE SYNTAX
POWERFUL LIBRARIES
CROSS-PLATFORM SUPPORT
API INTEGRATION
DATA PROCESSING
AUTOMATION
SECURITY TOOLINGYou do not need to become a full-time software developer to benefit from Python.
Your goal is to become comfortable enough to:
READ PYTHON
UNDERSTAND PYTHON
MODIFY PYTHON
WRITE SMALL SCRIPTS
PROCESS SECURITY DATA
AUTOMATE SECURITY TASKS
WORK WITH APIs
BUILD SECURITY UTILITIESThis module focuses on practical security outcomes.
Why Python Matters in Cybersecurity
Section titled “Why Python Matters in Cybersecurity”Security professionals constantly work with:
LOGS
IP ADDRESSES
DOMAINS
HASHES
JSON
CSV FILES
APIs
CLOUD EVENTS
VULNERABILITY DATA
THREAT INTELLIGENCE
SECURITY ALERTSPython allows you to transform these inputs into useful decisions.
Example:
10,000 LOG EVENTS ↓PYTHON ↓FILTER FAILED LOGINS ↓GROUP BY USER ↓IDENTIFY SUSPICIOUS ACCOUNTS ↓SECURITY ANALYST REVIEWPython Security Use Cases
Section titled “Python Security Use Cases”Python is commonly useful for:
LOG ANALYSIS
THREAT INTELLIGENCE
IOC PROCESSING
FILE HASHING
SECURITY AUTOMATION
API INTEGRATION
CLOUD SECURITY
VULNERABILITY MANAGEMENT
INCIDENT RESPONSE
REPORT GENERATION
ASSET INVENTORY
CONFIGURATION REVIEWPython Learning Path
Section titled “Python Learning Path”Follow this sequence:
PYTHON ENVIRONMENT ↓SYNTAX ↓VARIABLES ↓DATA TYPES ↓CONDITIONS ↓LOOPS ↓FUNCTIONS ↓LISTS / DICTIONARIES ↓FILES ↓EXCEPTIONS ↓MODULES ↓CSV ↓JSON ↓REGULAR EXPRESSIONS ↓HTTP / APIs ↓SECURITY DATA ↓AUTOMATION ↓SECURITY PROJECTS01 — Prepare Your Python Environment
Section titled “01 — Prepare Your Python Environment”Check whether Python is available:
python --versionor:
python3 --versionDepending on the environment, you may use:
Windows
Linux
macOS
VS Code
Terminal
PowerShellRecommended Project Structure
Section titled “Recommended Project Structure”Create:
python-cybersecurity/|+-- 01-basics/|+-- 02-files/|+-- 03-logs/|+-- 04-json/|+-- 05-csv/|+-- 06-regex/|+-- 07-apis/|+-- 08-automation/|+-- 09-projects/02 — Your First Python Program
Section titled “02 — Your First Python Program”Create:
hello_security.pyAdd:
print("Welcome to Python for Cybersecurity")Run:
python hello_security.pyor:
python3 hello_security.pyExpected output:
Welcome to Python for CybersecurityThe Basic Python Mental Model
Section titled “The Basic Python Mental Model”Python processes instructions from top to bottom.
INPUT ↓PYTHON LOGIC ↓OUTPUTFor security work:
LOG FILE ↓PYTHON SCRIPT ↓FILTER ↓RESULT03 — Variables
Section titled “03 — Variables”Variables store data.
Example:
username = "analyst01"ip_address = "10.10.10.25"failed_logins = 7Print them:
print(username)print(ip_address)print(failed_logins)Security Context
Section titled “Security Context”Variables might contain:
Username
IP Address
Hostname
Port
Severity
Event ID
Hash
Domain
Alert Count04 — Naming Variables
Section titled “04 — Naming Variables”Prefer descriptive names.
Good:
source_ip = "10.10.10.20"failed_login_count = 5alert_severity = "high"Avoid:
x = "10.10.10.20"a = 5z = "high"Security scripts become difficult to maintain when variable names are unclear.
05 — Data Types
Section titled “05 — Data Types”Common Python data types include:
STRING
INTEGER
FLOAT
BOOLEAN
LIST
DICTIONARY
TUPLE
SETStrings
Section titled “Strings”Strings represent text.
username = "analyst01"hostname = "WEB01"domain = "corp.example"Integers
Section titled “Integers”Integers represent whole numbers.
failed_logins = 10port = 443alert_count = 25Booleans
Section titled “Booleans”Booleans represent:
True
FalseExample:
is_admin = Falsemfa_enabled = TrueCheck a Data Type
Section titled “Check a Data Type”Use:
print(type(username))06 — String Operations
Section titled “06 — String Operations”Security data is frequently text.
Example:
event = "Failed login detected"Convert to lowercase:
print(event.lower())Convert to uppercase:
print(event.upper())Check whether text exists:
if "failed" in event.lower(): print("Authentication failure detected")07 — String Formatting
Section titled “07 — String Formatting”Use f-strings:
username = "analyst01"ip_address = "10.10.10.25"
print(f"User {username} connected from {ip_address}")Output:
User analyst01 connected from 10.10.10.2508 — User Input
Section titled “08 — User Input”Python can accept user input.
Example:
ip_address = input("Enter IP address: ")
print(f"Checking {ip_address}")Treat all user input as untrusted.
Validate it before using it in security-sensitive operations.
09 — Conditions
Section titled “09 — Conditions”Conditions allow Python to make decisions.
Example:
failed_logins = 12
if failed_logins > 10: print("Suspicious authentication activity")if / elif / else
Section titled “if / elif / else”failed_logins = 7
if failed_logins >= 10: print("High risk")elif failed_logins >= 5: print("Medium risk")else: print("Low risk")Security Decision Model
Section titled “Security Decision Model”EVENT ↓CONDITION ↓TRUE? ├── YES → ALERT └── NO → CONTINUE10 — Comparison Operators
Section titled “10 — Comparison Operators”Common operators:
== Equal
!= Not equal
> Greater than
< Less than
>= Greater or equal
<= Less or equalExample:
severity = "critical"
if severity == "critical": print("Escalate immediately")11 — Logical Operators
Section titled “11 — Logical Operators”Use:
and
or
notExample:
failed_logins = 15mfa_enabled = False
if failed_logins > 10 and not mfa_enabled: print("High-risk authentication condition")12 — Lists
Section titled “12 — Lists”Lists store multiple values.
Example:
suspicious_ips = [ "10.10.10.21", "10.10.10.34", "10.10.10.55"]Print:
print(suspicious_ips)Access the first item:
print(suspicious_ips[0])Add an Item
Section titled “Add an Item”suspicious_ips.append("10.10.10.99")Security Use Cases for Lists
Section titled “Security Use Cases for Lists”Lists are useful for:
IP Addresses
Domains
Users
Hosts
Indicators
Alert IDs
Vulnerable Assets13 — Loops
Section titled “13 — Loops”Loops repeat an operation.
Example:
suspicious_ips = [ "10.10.10.21", "10.10.10.34", "10.10.10.55"]
for ip in suspicious_ips: print(f"Reviewing {ip}")Security Loop Model
Section titled “Security Loop Model”FOR EACH ASSET ↓CHECK SECURITY CONDITION ↓RECORD RESULT14 — while Loops
Section titled “14 — while Loops”A while loop continues while a condition remains true.
Example:
attempt = 1
while attempt <= 3: print(f"Processing attempt {attempt}") attempt += 1Use while loops carefully to avoid infinite loops.
15 — Dictionaries
Section titled “15 — Dictionaries”Dictionaries store:
KEY:VALUEExample:
event = { "user": "analyst01", "source_ip": "10.10.10.25", "event_type": "failed_login", "severity": "medium"}Access:
print(event["user"])Why Dictionaries Matter
Section titled “Why Dictionaries Matter”Many security APIs return data shaped like dictionaries.
For example:
{ "user": "analyst01", "source_ip": "10.10.10.25", "severity": "high"}Understanding dictionaries prepares you for JSON.
16 — Nested Dictionaries
Section titled “16 — Nested Dictionaries”Example:
alert = { "id": 101, "user": { "name": "analyst01", "department": "security" }, "severity": "high"}Access:
print(alert["user"]["name"])17 — Sets
Section titled “17 — Sets”Sets store unique values.
Example:
source_ips = { "10.10.10.25", "10.10.10.25", "10.10.10.30"}Print:
print(source_ips)Duplicate entries are removed.
This is useful when processing repeated indicators.
18 — Tuples
Section titled “18 — Tuples”Tuples are ordered collections that are typically treated as immutable.
Example:
common_ports = (22, 80, 443)Tuples are useful when values should remain stable.
19 — Functions
Section titled “19 — Functions”Functions allow reusable logic.
Example:
def display_alert(message): print(f"ALERT: {message}")Call it:
display_alert("Multiple failed logins detected")Function Mental Model
Section titled “Function Mental Model”INPUT ↓FUNCTION ↓PROCESSING ↓OUTPUT20 — Function Parameters
Section titled “20 — Function Parameters”Example:
def analyze_login(username, failed_count): if failed_count >= 10: print(f"{username}: suspicious") else: print(f"{username}: normal")Call:
analyze_login("analyst01", 12)21 — Returning Values
Section titled “21 — Returning Values”Functions can return values.
Example:
def calculate_risk(failed_count): if failed_count >= 10: return "high" elif failed_count >= 5: return "medium" return "low"Then:
risk = calculate_risk(12)
print(risk)22 — Breaking Problems into Functions
Section titled “22 — Breaking Problems into Functions”Instead of one large script:
READ FILE
PARSE EVENT
CALCULATE RISK
GENERATE ALERT
WRITE REPORTcreate functions:
read_events()
parse_event()
calculate_risk()
create_alert()
write_report()This makes scripts easier to understand and maintain.
23 — Reading Files
Section titled “23 — Reading Files”Security professionals constantly process files.
Example:
with open("security.log", "r") as file: data = file.read()
print(data)Why Use with
Section titled “Why Use with”Using:
with open(...)automatically manages file closing.
24 — Read Files Line by Line
Section titled “24 — Read Files Line by Line”For large logs:
with open("security.log", "r") as file: for line in file: print(line.strip())This is usually better than loading a huge log entirely into memory.
25 — Search a Log
Section titled “25 — Search a Log”Suppose:
security.logcontains:
INFO Login successful user=analyst01WARNING Failed login user=admin01INFO Logout user=analyst01WARNING Failed login user=admin01Use:
with open("security.log", "r") as file: for line in file: if "Failed login" in line: print(line.strip())26 — Count Security Events
Section titled “26 — Count Security Events”Example:
failed_count = 0
with open("security.log", "r") as file: for line in file: if "Failed login" in line: failed_count += 1
print(f"Failed logins: {failed_count}")27 — Writing Files
Section titled “27 — Writing Files”Write results:
with open("report.txt", "w") as file: file.write("Security analysis completed\n")Append:
with open("report.txt", "a") as file: file.write("Suspicious login detected\n")28 — File Paths
Section titled “28 — File Paths”Use the pathlib module for modern path handling.
from pathlib import Path
log_file = Path("logs") / "security.log"
print(log_file)29 — Check Whether a File Exists
Section titled “29 — Check Whether a File Exists”from pathlib import Path
log_file = Path("security.log")
if log_file.exists(): print("Log found")else: print("Log not found")30 — Exception Handling
Section titled “30 — Exception Handling”Programs fail.
Common errors include:
File Not Found
Permission Denied
Invalid Data
Network Timeout
API FailureUse:
try: with open("security.log", "r") as file: print(file.read())except FileNotFoundError: print("Security log not found")31 — Generic Exception Handling
Section titled “31 — Generic Exception Handling”Avoid hiding every error with:
except:Prefer specific exceptions.
Example:
try: value = int("abc")except ValueError: print("Invalid number")32 — Modules
Section titled “32 — Modules”Modules provide reusable functionality.
Example:
import osimport jsonimport csvimport hashlib33 — Standard Library Security Modules
Section titled “33 — Standard Library Security Modules”Useful built-in modules include:
hashlib
json
csv
re
ipaddress
pathlib
datetime
logging
subprocess
socketUse privileged or system-execution capabilities carefully.
34 — File Hashing
Section titled “34 — File Hashing”Hashes help identify files.
Example:
import hashlib
file_path = "sample.txt"
sha256 = hashlib.sha256()
with open(file_path, "rb") as file: for chunk in iter(lambda: file.read(4096), b""): sha256.update(chunk)
print(sha256.hexdigest())Hashing Mental Model
Section titled “Hashing Mental Model”FILE ↓HASH FUNCTION ↓FIXED-LENGTH DIGESTSecurity uses include:
Integrity Checking
IOC Comparison
Malware Analysis
Evidence Verification35 — Build a File Hash Utility
Section titled “35 — Build a File Hash Utility”import hashlibfrom pathlib import Path
def calculate_sha256(file_path): path = Path(file_path)
if not path.exists(): return None
sha256 = hashlib.sha256()
with path.open("rb") as file: for chunk in iter(lambda: file.read(4096), b""): sha256.update(chunk)
return sha256.hexdigest()
result = calculate_sha256("sample.txt")
if result: print(f"SHA256: {result}")else: print("File not found")36 — IP Address Validation
Section titled “36 — IP Address Validation”Use:
import ipaddress
ip_value = "192.168.1.10"
try: ip = ipaddress.ip_address(ip_value) print(f"Valid IP: {ip}")except ValueError: print("Invalid IP")This is safer than assuming user-provided IP strings are valid.
37 — Check Private vs Public IP
Section titled “37 — Check Private vs Public IP”import ipaddress
ip = ipaddress.ip_address("10.10.10.20")
print(ip.is_private)38 — Regular Expressions
Section titled “38 — Regular Expressions”Regular expressions help search patterns in text.
Import:
import reExample:
text = "Connection from 192.168.1.25"
match = re.search(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", text)
if match: print(match.group())For strict IP validation, prefer ipaddress after extraction.
39 — Extract Multiple IP Addresses
Section titled “39 — Extract Multiple IP Addresses”import re
text = """Connections:192.168.1.2510.10.10.5"""
ips = re.findall(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", text)
for ip in ips: print(ip)40 — Security Regex Use Cases
Section titled “40 — Security Regex Use Cases”Regular expressions can help locate:
IP Addresses
Domains
Email Addresses
Hashes
Log Patterns
Ticket NumbersAvoid overly complex expressions when simpler parsing is possible.
41 — CSV Files
Section titled “41 — CSV Files”Security tools frequently export CSV.
Example:
user,source_ip,statusanalyst01,10.10.10.20,successadmin01,10.10.10.30,failedRead:
import csv
with open("events.csv", "r", newline="") as file: reader = csv.DictReader(file)
for row in reader: print(row["user"], row["status"])42 — Filter CSV Security Events
Section titled “42 — Filter CSV Security Events”import csv
with open("events.csv", "r", newline="") as file: reader = csv.DictReader(file)
for row in reader: if row["status"] == "failed": print(row)43 — Write a CSV Report
Section titled “43 — Write a CSV Report”import csv
results = [ { "user": "admin01", "failed_logins": 12, "risk": "high" }]
with open("report.csv", "w", newline="") as file: fieldnames = ["user", "failed_logins", "risk"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader() writer.writerows(results)44 — JSON
Section titled “44 — JSON”JSON is fundamental to security APIs.
Example:
{ "event": "failed_login", "user": "admin01", "severity": "high"}Read JSON
Section titled “Read JSON”import json
with open("alert.json", "r") as file: alert = json.load(file)
print(alert["user"])45 — Convert JSON String to Python
Section titled “45 — Convert JSON String to Python”import json
data = """{ "user": "admin01", "severity": "high"}"""
event = json.loads(data)
print(event["severity"])46 — Convert Python to JSON
Section titled “46 — Convert Python to JSON”import json
alert = { "user": "admin01", "severity": "high"}
print(json.dumps(alert, indent=4))47 — Work with Nested JSON
Section titled “47 — Work with Nested JSON”event = { "user": { "name": "admin01", "department": "IT" }, "source": { "ip": "10.10.10.25" }}
print(event["source"]["ip"])48 — Dates and Time
Section titled “48 — Dates and Time”Security events rely heavily on timestamps.
Use:
from datetime import datetime
current_time = datetime.now()
print(current_time)Format:
print(current_time.strftime("%Y-%m-%d %H:%M:%S"))49 — Logging
Section titled “49 — Logging”Production-quality scripts should use logging instead of only print().
Example:
import logging
logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.info("Security analysis started")logging.warning("Suspicious event detected")50 — Logging Levels
Section titled “50 — Logging Levels”Common levels:
DEBUG
INFO
WARNING
ERROR
CRITICALDo not log secrets.
51 — HTTP and APIs
Section titled “51 — HTTP and APIs”Many security platforms expose APIs.
Conceptually:
PYTHON SCRIPT ↓HTTP REQUEST ↓SECURITY PLATFORM ↓JSON RESPONSE ↓PYTHON PROCESSING52 — Using the Requests Library
Section titled “52 — Using the Requests Library”A commonly used third-party library is:
requestsInstall inside your own development environment as appropriate:
python -m pip install requests53 — Basic GET Request
Section titled “53 — Basic GET Request”Against an authorized training API:
import requests
response = requests.get( "https://example.invalid/api/status", timeout=10)
print(response.status_code)Replace the placeholder only with an API you are authorized to use.
54 — Parse JSON API Response
Section titled “54 — Parse JSON API Response”data = response.json()
print(data)55 — Add Request Headers
Section titled “55 — Add Request Headers”headers = { "Accept": "application/json"}
response = requests.get( "https://example.invalid/api/events", headers=headers, timeout=10)56 — API Authentication
Section titled “56 — API Authentication”Security APIs may use:
API Keys
Bearer Tokens
OAuth
Session AuthenticationNever hard-code secrets directly into source files.
Bad:
api_key = "real-secret-value"Prefer environment variables.
57 — Environment Variables
Section titled “57 — Environment Variables”Example:
import os
api_key = os.getenv("SECURITY_API_KEY")
if api_key is None: print("API key not configured")Security Principle
Section titled “Security Principle”CODE≠SECRET STORAGE58 — Build a Safe API Client
Section titled “58 — Build a Safe API Client”import osimport requests
api_key = os.getenv("SECURITY_API_KEY")
if not api_key: raise RuntimeError("SECURITY_API_KEY is not configured")
headers = { "Authorization": f"Bearer {api_key}", "Accept": "application/json"}
response = requests.get( "https://example.invalid/api/events", headers=headers, timeout=10)
response.raise_for_status()
events = response.json()
print(events)59 — Handle API Errors
Section titled “59 — Handle API Errors”import requests
try: response = requests.get( "https://example.invalid/api/status", timeout=10 )
response.raise_for_status()
except requests.Timeout: print("Request timed out")
except requests.RequestException as error: print(f"API request failed: {error}")60 — Threat Intelligence Workflow
Section titled “60 — Threat Intelligence Workflow”A typical security automation flow might be:
IOC ↓VALIDATE ↓QUERY AUTHORIZED API ↓RECEIVE CONTEXT ↓ASSIGN RISK ↓REPORT61 — Build an IOC Data Structure
Section titled “61 — Build an IOC Data Structure”ioc = { "type": "ip", "value": "203.0.113.25", "source": "training", "status": "unknown"}62 — Indicator Processing
Section titled “62 — Indicator Processing”You can process a list:
indicators = [ {"type": "ip", "value": "203.0.113.25"}, {"type": "domain", "value": "example.invalid"}]
for indicator in indicators: print( indicator["type"], indicator["value"] )63 — Failed Login Analyzer
Section titled “63 — Failed Login Analyzer”Suppose you have:
auth.logwith training entries:
FAILED user=admin01 ip=10.10.10.20FAILED user=admin01 ip=10.10.10.21SUCCESS user=analyst01 ip=10.10.10.30FAILED user=admin01 ip=10.10.10.22Create:
failed_logins = {}
with open("auth.log", "r") as file: for line in file: if line.startswith("FAILED"): parts = line.split()
user = parts[1].split("=")[1]
failed_logins[user] = ( failed_logins.get(user, 0) + 1 )
for user, count in failed_logins.items(): print(f"{user}: {count}")64 — Add Risk Classification
Section titled “64 — Add Risk Classification”def classify_failed_logins(count): if count >= 10: return "high" elif count >= 5: return "medium" return "low"Then:
for user, count in failed_logins.items(): risk = classify_failed_logins(count)
print( f"{user}: {count} failed logins - {risk}" )65 — Build a Security Report
Section titled “65 — Build a Security Report”Output might look like:
User: admin01Failed Logins: 12Risk: HIGHThe automation should support the analyst, not automatically assume compromise.
66 — Asset Inventory Processing
Section titled “66 — Asset Inventory Processing”Example data:
assets = [ { "hostname": "WEB01", "ip": "10.10.10.20", "criticality": "high" }, { "hostname": "WS01", "ip": "10.10.10.30", "criticality": "medium" }]Filter high-value assets:
for asset in assets: if asset["criticality"] == "high": print(asset["hostname"])67 — Vulnerability Data Processing
Section titled “67 — Vulnerability Data Processing”Example:
findings = [ { "asset": "WEB01", "severity": "high" }, { "asset": "WS01", "severity": "low" }]Filter:
for finding in findings: if finding["severity"] in ["high", "critical"]: print(finding)68 — Sorting Security Data
Section titled “68 — Sorting Security Data”Example:
alerts = [ {"id": 1, "score": 40}, {"id": 2, "score": 90}, {"id": 3, "score": 70}]
sorted_alerts = sorted( alerts, key=lambda alert: alert["score"], reverse=True)
print(sorted_alerts)69 — Counting Events
Section titled “69 — Counting Events”Use dictionaries or collections.Counter.
Example:
from collections import Counter
events = [ "login_failed", "login_failed", "malware_alert", "login_success"]
counts = Counter(events)
print(counts)70 — Deduplicating Indicators
Section titled “70 — Deduplicating Indicators”Using a set:
ips = [ "10.10.10.20", "10.10.10.20", "10.10.10.30"]
unique_ips = set(ips)
print(unique_ips)71 — List Comprehensions
Section titled “71 — List Comprehensions”A compact way to transform lists.
Example:
high_risk = [ alert for alert in alerts if alert["score"] >= 80]Use them when they remain readable.
72 — Comprehensibility Matters
Section titled “72 — Comprehensibility Matters”Do not write complex one-line code merely because Python allows it.
Security automation should optimize for:
READABILITY
AUDITABILITY
MAINTAINABILITY73 — Classes: What You Need to Know
Section titled “73 — Classes: What You Need to Know”You do not need advanced object-oriented programming immediately.
Understand the basic idea:
CLASS=BLUEPRINT
OBJECT=INSTANCEExample:
class SecurityAlert: def __init__(self, alert_id, severity): self.alert_id = alert_id self.severity = severity
def display(self): print( f"{self.alert_id}: {self.severity}" )74 — When Classes Become Useful
Section titled “74 — When Classes Become Useful”Classes can help when building larger tools involving repeated objects such as:
Alerts
Assets
Indicators
Findings
Users
IncidentsFor beginner automation, functions and dictionaries are often enough.
75 — Virtual Environments
Section titled “75 — Virtual Environments”Different Python projects may require different dependencies.
Create a virtual environment:
python -m venv .venvOn Windows PowerShell:
.\.venv\Scripts\Activate.ps1On Linux/macOS:
source .venv/bin/activateWhy Virtual Environments Matter
Section titled “Why Virtual Environments Matter”They help keep:
PROJECT A DEPENDENCIESseparate from:
PROJECT B DEPENDENCIES76 — Dependency Management
Section titled “76 — Dependency Management”View installed packages:
python -m pip listExport dependencies:
python -m pip freeze > requirements.txtDo not blindly install large dependency files from untrusted sources.
77 — Secure Use of External Libraries
Section titled “77 — Secure Use of External Libraries”Before adding a package consider:
Do I Need It?
Is It Maintained?
Is It From the Expected Source?
Does It Introduce Unnecessary Risk?
Can the Standard Library Do the Job?78 — subprocess
Section titled “78 — subprocess”Python can launch operating-system programs.
Example:
import subprocess
result = subprocess.run( ["python", "--version"], capture_output=True, text=True, check=False)
print(result.stdout or result.stderr)subprocess Security Rule
Section titled “subprocess Security Rule”Prefer:
["command", "argument"]rather than constructing shell command strings from untrusted input.
Avoid unnecessary:
shell=Trueespecially with external input.
79 — Input Validation
Section titled “79 — Input Validation”Suppose a script accepts a port:
port = input("Enter port: ")Validate it:
try: port = int(port)
if 1 <= port <= 65535: print("Valid port") else: print("Port out of range")
except ValueError: print("Port must be numeric")80 — Secure Script Design
Section titled “80 — Secure Script Design”Every security script should consider:
INPUT VALIDATION
LEAST PRIVILEGE
SECRET HANDLING
ERROR HANDLING
TIMEOUTS
LOGGING
OUTPUT SANITIZATION
DEPENDENCY SECURITY81 — Avoid Running as Administrator Unnecessarily
Section titled “81 — Avoid Running as Administrator Unnecessarily”Ask:
Does This ScriptActually NeedAdministrative Rights?If not:
RUN IT ASA STANDARD USER82 — Avoid Hard-Coded Paths
Section titled “82 — Avoid Hard-Coded Paths”Instead of:
log_file = "C:\\Users\\analyst\\logs\\security.log"prefer configurable or relative paths where appropriate.
83 — Add Command-Line Arguments
Section titled “83 — Add Command-Line Arguments”Python’s argparse can help.
Example:
import argparse
parser = argparse.ArgumentParser( description="Analyze a security log")
parser.add_argument( "logfile", help="Path to the log file")
args = parser.parse_args()
print(args.logfile)84 — Build Reusable Security Utilities
Section titled “84 — Build Reusable Security Utilities”Good security scripts often have:
INPUT
VALIDATION
PROCESSING
OUTPUT
ERROR HANDLING
LOGGINGStructure:
def main(): pass
if __name__ == "__main__": main()85 — Why main() Helps
Section titled “85 — Why main() Helps”It creates a clear entry point.
Conceptually:
IMPORTS
FUNCTIONS
MAIN WORKFLOW
PROGRAM START86 — Security Automation Architecture
Section titled “86 — Security Automation Architecture”A mature script may look like:
CONFIGURATION ↓COLLECT DATA ↓VALIDATE ↓NORMALIZE ↓ANALYZE ↓ENRICH ↓SCORE ↓REPORT87 — Normalize Security Data
Section titled “87 — Normalize Security Data”Different tools may represent severity as:
HIGH
High
high
4
criticalNormalize before analysis.
Example:
severity = severity.strip().lower()88 — Build a Risk Scoring Function
Section titled “88 — Build a Risk Scoring Function”Example:
def calculate_risk(severity, asset_criticality): scores = { "low": 1, "medium": 2, "high": 3, "critical": 4 }
return ( scores.get(severity, 0) + scores.get(asset_criticality, 0) )This is a simplified learning model, not a substitute for formal enterprise risk methodology.
89 — Security Automation Should Support Human Decisions
Section titled “89 — Security Automation Should Support Human Decisions”Avoid designing:
ONE ALERT ↓AUTOMATIC DESTRUCTIVE RESPONSEwithout appropriate controls.
Prefer:
ALERT ↓COLLECT CONTEXT ↓SCORE ↓ANALYST REVIEW ↓APPROVED RESPONSEfor high-impact actions.
90 — Project 01: Security Log Analyzer
Section titled “90 — Project 01: Security Log Analyzer”Build a script that:
Reads a Log File
Finds Failed Logins
Counts Failures by User
Counts Failures by IP
Assigns Risk
Generates ReportProject Architecture
Section titled “Project Architecture”AUTH LOG ↓READ ↓PARSE ↓COUNT ↓ANALYZE ↓REPORT91 — Project 02: File Hash Utility
Section titled “91 — Project 02: File Hash Utility”Build:
INPUT FILE ↓SHA-256 ↓OUTPUT HASH ↓SAVE REPORTFeatures:
File Existence Check
SHA-256
Timestamp
Readable Output
Error Handling92 — Project 03: IOC Deduplication Tool
Section titled “92 — Project 03: IOC Deduplication Tool”Input:
IOC LISTProcess:
Read
Normalize
Remove Duplicates
Validate
SortOutput:
Clean IOC List93 — Project 04: Vulnerability Report Parser
Section titled “93 — Project 04: Vulnerability Report Parser”Input:
CSV VULNERABILITY EXPORTProcess:
Read CSV
Filter High / Critical
Group by Asset
Count Findings
PrioritizeOutput:
Security Summary94 — Project 05: Security API Collector
Section titled “94 — Project 05: Security API Collector”In an authorized training API:
API ↓AUTHENTICATE ↓COLLECT EVENTS ↓PARSE JSON ↓FILTER ↓REPORTEnsure credentials are stored securely.
95 — Project 06: Asset Inventory Analyzer
Section titled “95 — Project 06: Asset Inventory Analyzer”Input:
Asset CSV / JSONAnalyze:
Hostname
IP
OS
Owner
Criticality
EnvironmentIdentify:
Missing Owners
Unknown Criticality
Duplicate Assets
Incomplete Records96 — Project 07: Failed Login Investigation Tool
Section titled “96 — Project 07: Failed Login Investigation Tool”Build:
LOGIN EVENTS ↓GROUP BY USER ↓GROUP BY SOURCE IP ↓COUNT FAILURES ↓IDENTIFY OUTLIERS ↓GENERATE INVESTIGATION SUMMARY97 — Project 08: Cloud Security Data Parser
Section titled “97 — Project 08: Cloud Security Data Parser”Use synthetic exported cloud data such as:
Users
Roles
Security Groups
Storage Resources
Audit EventsPython can:
Parse
Filter
Compare
Report98 — Python for SOC Analysts
Section titled “98 — Python for SOC Analysts”Focus on:
Log Parsing
Alert Enrichment
IOC Processing
API Integration
CSV / JSON
Report Generation99 — Python for Penetration Testers
Section titled “99 — Python for Penetration Testers”Focus on authorized workflows such as:
Result Parsing
Data Organization
Evidence Processing
Asset Analysis
API Interaction
Report AutomationThe objective is to automate repetitive assessment tasks, not indiscriminate scanning or exploitation.
100 — Python for Cloud Security Engineers
Section titled “100 — Python for Cloud Security Engineers”Focus on:
Cloud APIs
IAM Data
Resource Inventory
Security Configuration
Audit Events
Compliance Checks101 — Python for Incident Responders
Section titled “101 — Python for Incident Responders”Focus on:
Evidence Parsing
Hashing
Timeline Processing
Log Analysis
IOC Correlation
Report Generation102 — Python for Threat Hunters
Section titled “102 — Python for Threat Hunters”Focus on:
Large Log Sets
Indicators
Event Correlation
Baselines
Anomaly Summaries
Threat Intelligence103 — Python for AppSec
Section titled “103 — Python for AppSec”Focus on:
API Data
Source Analysis Support
Dependency Data
Security Test Results
Reporting
Security Automation104 — Python Learning Strategy
Section titled “104 — Python Learning Strategy”Use:
READ ↓TYPE ↓RUN ↓MODIFY ↓BREAK ↓DEBUG ↓APPLYDo not simply copy and paste examples.
Change them.
105 — Debugging Methodology
Section titled “105 — Debugging Methodology”When something fails:
READ ERROR MESSAGE ↓IDENTIFY ERROR TYPE ↓IDENTIFY LINE ↓CHECK INPUT ↓CHECK DATA TYPE ↓CHECK ASSUMPTION ↓FIX ↓RUN AGAIN106 — Common Python Errors
Section titled “106 — Common Python Errors”Expect:
SyntaxError
NameError
TypeError
ValueError
KeyError
FileNotFoundError
ModuleNotFoundErrorLearning to interpret these errors is a core programming skill.
107 — Example KeyError
Section titled “107 — Example KeyError”This fails if the key does not exist:
event = { "user": "analyst01"}
print(event["severity"])Safer:
print(event.get("severity", "unknown"))108 — Example Type Conversion
Section titled “108 — Example Type Conversion”Input returns a string:
count = input("Enter failed login count: ")Convert:
count = int(count)with appropriate exception handling.
109 — Code Quality Checklist
Section titled “109 — Code Quality Checklist”Before considering a script complete:
Does It Have a Clear Purpose?
Are Variable Names Clear?
Are Functions Small?
Is Input Validated?
Are Errors Handled?
Are Secrets Protected?
Are Logs Safe?
Are Dependencies Necessary?
Is Output Understandable?
Is the Script Documented?110 — Documentation Template
Section titled “110 — Documentation Template”Every portfolio script should include:
Project Name:
Security Problem:
Purpose:
Requirements:
Input:
Output:
How to Run:
Security Considerations:
Limitations:
Example:111 — README Structure
Section titled “111 — README Structure”Example:
# Failed Login Analyzer
## Purpose
## Requirements
## Input Format
## Usage
## Output
## Security Considerations
## Limitations112 — Testing Your Code
Section titled “112 — Testing Your Code”Test:
VALID INPUT
EMPTY INPUT
INVALID INPUT
MISSING FILE
MALFORMED JSON
API TIMEOUT
NO RESULTS
LARGE INPUT113 — Secure Development Workflow
Section titled “113 — Secure Development Workflow”Use:
WRITE ↓TEST ↓REVIEW ↓FIX ↓DOCUMENT ↓COMMIT114 — Never Commit Secrets
Section titled “114 — Never Commit Secrets”Before pushing code, check for:
API Keys
Passwords
Tokens
Private Keys
Internal URLs
Sensitive Data115 — Git Ignore
Section titled “115 — Git Ignore”Sensitive or local files may belong in:
.gitignoreExamples might include:
.env
.venv/
__pycache__/
local-results/
sensitive-data/depending on the project.
116 — Python Security Readiness Levels
Section titled “116 — Python Security Readiness Levels”Level 01 — Syntax
Section titled “Level 01 — Syntax”You understand:
Variables
Strings
Numbers
Conditions
LoopsLevel 02 — Structured Data
Section titled “Level 02 — Structured Data”You understand:
Lists
Dictionaries
Sets
FunctionsLevel 03 — Files
Section titled “Level 03 — Files”You can process:
Logs
CSV
JSONLevel 04 — Security Data
Section titled “Level 04 — Security Data”You can:
Parse
Filter
Count
Group
NormalizeLevel 05 — APIs
Section titled “Level 05 — APIs”You can:
Call APIs
Authenticate Safely
Parse Responses
Handle ErrorsLevel 06 — Automation
Section titled “Level 06 — Automation”You can:
Collect
Analyze
Enrich
Score
ReportLevel 07 — Security Utility Development
Section titled “Level 07 — Security Utility Development”You can create reusable:
Log Analyzers
IOC Utilities
Asset Tools
Reporting Tools
API Collectors117 — 4-Week Python Practice Plan
Section titled “117 — 4-Week Python Practice Plan”| Week | Focus |
|---|---|
| 1 | Variables, Conditions, Loops, Functions |
| 2 | Files, Logs, CSV, JSON |
| 3 | Regex, Hashing, APIs, Error Handling |
| 4 | Security Automation Project |
118 — Daily Practice Pattern
Section titled “118 — Daily Practice Pattern”Spend your practice time roughly like:
20%READ CONCEPT30%TYPE EXAMPLES50%SOLVE SECURITY PROBLEMThe goal is to use Python, not memorize Python.
Python for Cybersecurity Checklist
Section titled “Python for Cybersecurity Checklist”Fundamentals
Section titled “Fundamentals”- Python installed
- Scripts can be executed
- Variables understood
- Data types understood
- Conditions understood
- Loops understood
- Functions understood
Collections
Section titled “Collections”- Lists
- Dictionaries
- Sets
- Tuples
- Nested data
- Read text files
- Write files
- Process line by line
- Handle missing files
- Work with paths
Security Data
Section titled “Security Data”- Parse logs
- Count events
- Deduplicate data
- Filter findings
- Normalize values
- Sort results
- Read CSV
- Filter rows
- Write reports
- Use
DictReader - Use
DictWriter
- Read JSON
- Write JSON
- Parse nested objects
- Convert strings
- Handle malformed data
Security Utilities
Section titled “Security Utilities”- SHA-256 hashing
- IP validation
- Regex basics
- Timestamp handling
- Logging
- Understand HTTP requests
- Make authorized GET requests
- Parse JSON responses
- Use timeouts
- Handle errors
- Protect API credentials
Secure Coding
Section titled “Secure Coding”- Validate input
- Avoid hard-coded secrets
- Use least privilege
- Handle errors
- Protect logs
- Review dependencies
- Avoid unsafe shell construction
Projects
Section titled “Projects”- Log analyzer
- Hash calculator
- IOC cleaner
- Vulnerability parser
- API collector
- Asset analyzer
40 Python for Cybersecurity Review Questions
Section titled “40 Python for Cybersecurity Review Questions”- Why is Python useful in cybersecurity?
- What is a variable?
- What is a string?
- What is an integer?
- What is a boolean?
- What is a list?
- What is a dictionary?
- Why are dictionaries important when working with APIs?
- What is a set?
- When are sets useful for security data?
- What is a loop?
- What does a condition do?
- What is a function?
- Why should large scripts be separated into functions?
- What does
returndo? - Why is
with open()useful? - Why should large log files often be processed line by line?
- What is exception handling?
- Why should specific exceptions be preferred?
- What is a Python module?
- What does
hashlibprovide? - What is SHA-256 used for?
- What does the
ipaddressmodule provide? - What is a regular expression?
- When should regex not replace proper data validation?
- What is CSV?
- What is JSON?
- How does JSON map to Python dictionaries and lists?
- Why are timestamps important in security investigations?
- Why is structured logging useful?
- What is an API?
- Why should API requests use timeouts?
- Why should API credentials not be hard-coded?
- What are environment variables?
- What is a virtual environment?
- Why should external Python packages be reviewed before installation?
- Why can
shell=Truebe dangerous with untrusted input? - Why should security automation run with least privilege?
- Why should scripts be tested with invalid inputs?
- What makes a Python security script production-ready?
Final Python for Cybersecurity Mental Model
Section titled “Final Python for Cybersecurity Mental Model”Remember:
SECURITY DATA ↓PYTHON ↓VALIDATE ↓PARSE ↓NORMALIZE ↓ANALYZE ↓ENRICH ↓DECIDE ↓REPORTDo not think:
I MUST MEMORIZEALL OF PYTHONThink:
I NEED TO UNDERSTANDTHE SECURITY PROBLEM ↓BREAK IT INTOSMALL LOGICAL STEPS ↓USE PYTHONTO AUTOMATE THOSE STEPSFor example:
LOG FILE ↓READ ↓FILTER ↓COUNT ↓RISK ↓REPORTor:
SECURITY API ↓REQUEST ↓JSON ↓PARSE ↓FILTER ↓SECURITY RESULTor:
VULNERABILITY CSV ↓READ ↓FILTER HIGH RISK ↓GROUP BY ASSET ↓PRIORITIZE ↓REPORTThat is Python for cybersecurity.
What’s Next?
Section titled “What’s Next?”➡️ 02 — Bash for Cybersecurity
The next module moves into Linux command-line and shell automation.
You will learn:
LINUX SHELL ↓FILES ↓PERMISSIONS ↓PROCESSES ↓PIPES ↓REDIRECTION ↓grep ↓awk ↓sed ↓NETWORK COMMANDS ↓BASH VARIABLES ↓CONDITIONS ↓LOOPS ↓FUNCTIONS ↓SHELL SCRIPTS ↓SECURITY AUTOMATIONThe objective will be to use Bash as a practical tool for Linux security operations, log analysis, incident response, cloud administration, system assessment, and repeatable security workflows.