Skip to content

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 TOOLING

You 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 UTILITIES

This module focuses on practical security outcomes.

Security professionals constantly work with:

LOGS
IP ADDRESSES
DOMAINS
HASHES
JSON
CSV FILES
APIs
CLOUD EVENTS
VULNERABILITY DATA
THREAT INTELLIGENCE
SECURITY ALERTS

Python 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 REVIEW

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 REVIEW

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 PROJECTS

Check whether Python is available:

Terminal window
python --version

or:

Terminal window
python3 --version

Depending on the environment, you may use:

Windows
Linux
macOS
VS Code
Terminal
PowerShell

Create:

python-cybersecurity/
|
+-- 01-basics/
|
+-- 02-files/
|
+-- 03-logs/
|
+-- 04-json/
|
+-- 05-csv/
|
+-- 06-regex/
|
+-- 07-apis/
|
+-- 08-automation/
|
+-- 09-projects/

Create:

hello_security.py

Add:

print("Welcome to Python for Cybersecurity")

Run:

Terminal window
python hello_security.py

or:

Terminal window
python3 hello_security.py

Expected output:

Welcome to Python for Cybersecurity

Python processes instructions from top to bottom.

INPUT
PYTHON LOGIC
OUTPUT

For security work:

LOG FILE
PYTHON SCRIPT
FILTER
RESULT

Variables store data.

Example:

username = "analyst01"
ip_address = "10.10.10.25"
failed_logins = 7

Print them:

print(username)
print(ip_address)
print(failed_logins)

Variables might contain:

Username
IP Address
Hostname
Port
Severity
Event ID
Hash
Domain
Alert Count

Prefer descriptive names.

Good:

source_ip = "10.10.10.20"
failed_login_count = 5
alert_severity = "high"

Avoid:

x = "10.10.10.20"
a = 5
z = "high"

Security scripts become difficult to maintain when variable names are unclear.

Common Python data types include:

STRING
INTEGER
FLOAT
BOOLEAN
LIST
DICTIONARY
TUPLE
SET

Strings represent text.

username = "analyst01"
hostname = "WEB01"
domain = "corp.example"

Integers represent whole numbers.

failed_logins = 10
port = 443
alert_count = 25

Booleans represent:

True
False

Example:

is_admin = False
mfa_enabled = True

Use:

print(type(username))

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")

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.25

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.

Conditions allow Python to make decisions.

Example:

failed_logins = 12
if failed_logins > 10:
print("Suspicious authentication activity")
failed_logins = 7
if failed_logins >= 10:
print("High risk")
elif failed_logins >= 5:
print("Medium risk")
else:
print("Low risk")
EVENT
CONDITION
TRUE?
├── YES → ALERT
└── NO → CONTINUE

Common operators:

== Equal
!= Not equal
> Greater than
< Less than
>= Greater or equal
<= Less or equal

Example:

severity = "critical"
if severity == "critical":
print("Escalate immediately")

Use:

and
or
not

Example:

failed_logins = 15
mfa_enabled = False
if failed_logins > 10 and not mfa_enabled:
print("High-risk authentication condition")

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])
suspicious_ips.append("10.10.10.99")

Lists are useful for:

IP Addresses
Domains
Users
Hosts
Indicators
Alert IDs
Vulnerable Assets

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}")
FOR EACH ASSET
CHECK SECURITY CONDITION
RECORD RESULT

A while loop continues while a condition remains true.

Example:

attempt = 1
while attempt <= 3:
print(f"Processing attempt {attempt}")
attempt += 1

Use while loops carefully to avoid infinite loops.

Dictionaries store:

KEY
:
VALUE

Example:

event = {
"user": "analyst01",
"source_ip": "10.10.10.25",
"event_type": "failed_login",
"severity": "medium"
}

Access:

print(event["user"])

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.

Example:

alert = {
"id": 101,
"user": {
"name": "analyst01",
"department": "security"
},
"severity": "high"
}

Access:

print(alert["user"]["name"])

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.

Tuples are ordered collections that are typically treated as immutable.

Example:

common_ports = (22, 80, 443)

Tuples are useful when values should remain stable.

Functions allow reusable logic.

Example:

def display_alert(message):
print(f"ALERT: {message}")

Call it:

display_alert("Multiple failed logins detected")
INPUT
FUNCTION
PROCESSING
OUTPUT

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)

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)

Instead of one large script:

READ FILE
PARSE EVENT
CALCULATE RISK
GENERATE ALERT
WRITE REPORT

create functions:

read_events()
parse_event()
calculate_risk()
create_alert()
write_report()

This makes scripts easier to understand and maintain.

Security professionals constantly process files.

Example:

with open("security.log", "r") as file:
data = file.read()
print(data)

Using:

with open(...)

automatically manages file closing.

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.

Suppose:

security.log

contains:

INFO Login successful user=analyst01
WARNING Failed login user=admin01
INFO Logout user=analyst01
WARNING Failed login user=admin01

Use:

with open("security.log", "r") as file:
for line in file:
if "Failed login" in line:
print(line.strip())

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}")

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")

Use the pathlib module for modern path handling.

from pathlib import Path
log_file = Path("logs") / "security.log"
print(log_file)
from pathlib import Path
log_file = Path("security.log")
if log_file.exists():
print("Log found")
else:
print("Log not found")

Programs fail.

Common errors include:

File Not Found
Permission Denied
Invalid Data
Network Timeout
API Failure

Use:

try:
with open("security.log", "r") as file:
print(file.read())
except FileNotFoundError:
print("Security log not found")

Avoid hiding every error with:

except:

Prefer specific exceptions.

Example:

try:
value = int("abc")
except ValueError:
print("Invalid number")

Modules provide reusable functionality.

Example:

import os
import json
import csv
import hashlib

Useful built-in modules include:

hashlib
json
csv
re
ipaddress
pathlib
datetime
logging
subprocess
socket

Use privileged or system-execution capabilities carefully.

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())
FILE
HASH FUNCTION
FIXED-LENGTH DIGEST

Security uses include:

Integrity Checking
IOC Comparison
Malware Analysis
Evidence Verification
import hashlib
from 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")

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.

import ipaddress
ip = ipaddress.ip_address("10.10.10.20")
print(ip.is_private)

Regular expressions help search patterns in text.

Import:

import re

Example:

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.

import re
text = """
Connections:
192.168.1.25
10.10.10.5
"""
ips = re.findall(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", text)
for ip in ips:
print(ip)

Regular expressions can help locate:

IP Addresses
Domains
Email Addresses
Hashes
Log Patterns
Ticket Numbers

Avoid overly complex expressions when simpler parsing is possible.

Security tools frequently export CSV.

Example:

user,source_ip,status
analyst01,10.10.10.20,success
admin01,10.10.10.30,failed

Read:

import csv
with open("events.csv", "r", newline="") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["user"], row["status"])
import csv
with open("events.csv", "r", newline="") as file:
reader = csv.DictReader(file)
for row in reader:
if row["status"] == "failed":
print(row)
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)

JSON is fundamental to security APIs.

Example:

{
"event": "failed_login",
"user": "admin01",
"severity": "high"
}
import json
with open("alert.json", "r") as file:
alert = json.load(file)
print(alert["user"])
import json
data = """
{
"user": "admin01",
"severity": "high"
}
"""
event = json.loads(data)
print(event["severity"])
import json
alert = {
"user": "admin01",
"severity": "high"
}
print(json.dumps(alert, indent=4))
event = {
"user": {
"name": "admin01",
"department": "IT"
},
"source": {
"ip": "10.10.10.25"
}
}
print(event["source"]["ip"])

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"))

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")

Common levels:

DEBUG
INFO
WARNING
ERROR
CRITICAL

Do not log secrets.

Many security platforms expose APIs.

Conceptually:

PYTHON SCRIPT
HTTP REQUEST
SECURITY PLATFORM
JSON RESPONSE
PYTHON PROCESSING

A commonly used third-party library is:

requests

Install inside your own development environment as appropriate:

Terminal window
python -m pip install requests

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.

data = response.json()
print(data)
headers = {
"Accept": "application/json"
}
response = requests.get(
"https://example.invalid/api/events",
headers=headers,
timeout=10
)

Security APIs may use:

API Keys
Bearer Tokens
OAuth
Session Authentication

Never hard-code secrets directly into source files.

Bad:

api_key = "real-secret-value"

Prefer environment variables.

Example:

import os
api_key = os.getenv("SECURITY_API_KEY")
if api_key is None:
print("API key not configured")
CODE
SECRET STORAGE
import os
import 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)
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}")

A typical security automation flow might be:

IOC
VALIDATE
QUERY AUTHORIZED API
RECEIVE CONTEXT
ASSIGN RISK
REPORT
ioc = {
"type": "ip",
"value": "203.0.113.25",
"source": "training",
"status": "unknown"
}

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"]
)

Suppose you have:

auth.log

with training entries:

FAILED user=admin01 ip=10.10.10.20
FAILED user=admin01 ip=10.10.10.21
SUCCESS user=analyst01 ip=10.10.10.30
FAILED user=admin01 ip=10.10.10.22

Create:

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}")
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}"
)

Output might look like:

User: admin01
Failed Logins: 12
Risk: HIGH

The automation should support the analyst, not automatically assume compromise.

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"])

Example:

findings = [
{
"asset": "WEB01",
"severity": "high"
},
{
"asset": "WS01",
"severity": "low"
}
]

Filter:

for finding in findings:
if finding["severity"] in ["high", "critical"]:
print(finding)

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)

Use dictionaries or collections.Counter.

Example:

from collections import Counter
events = [
"login_failed",
"login_failed",
"malware_alert",
"login_success"
]
counts = Counter(events)
print(counts)

Using a set:

ips = [
"10.10.10.20",
"10.10.10.20",
"10.10.10.30"
]
unique_ips = set(ips)
print(unique_ips)

A compact way to transform lists.

Example:

high_risk = [
alert
for alert in alerts
if alert["score"] >= 80
]

Use them when they remain readable.

Do not write complex one-line code merely because Python allows it.

Security automation should optimize for:

READABILITY
AUDITABILITY
MAINTAINABILITY

You do not need advanced object-oriented programming immediately.

Understand the basic idea:

CLASS
=
BLUEPRINT
OBJECT
=
INSTANCE

Example:

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}"
)

Classes can help when building larger tools involving repeated objects such as:

Alerts
Assets
Indicators
Findings
Users
Incidents

For beginner automation, functions and dictionaries are often enough.

Different Python projects may require different dependencies.

Create a virtual environment:

Terminal window
python -m venv .venv

On Windows PowerShell:

Terminal window
.\.venv\Scripts\Activate.ps1

On Linux/macOS:

Terminal window
source .venv/bin/activate

They help keep:

PROJECT A DEPENDENCIES

separate from:

PROJECT B DEPENDENCIES

View installed packages:

Terminal window
python -m pip list

Export dependencies:

Terminal window
python -m pip freeze > requirements.txt

Do not blindly install large dependency files from untrusted sources.

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?

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)

Prefer:

["command", "argument"]

rather than constructing shell command strings from untrusted input.

Avoid unnecessary:

shell=True

especially with external input.

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")

Every security script should consider:

INPUT VALIDATION
LEAST PRIVILEGE
SECRET HANDLING
ERROR HANDLING
TIMEOUTS
LOGGING
OUTPUT SANITIZATION
DEPENDENCY SECURITY

81 — Avoid Running as Administrator Unnecessarily

Section titled “81 — Avoid Running as Administrator Unnecessarily”

Ask:

Does This Script
Actually Need
Administrative Rights?

If not:

RUN IT AS
A STANDARD USER

Instead of:

log_file = "C:\\Users\\analyst\\logs\\security.log"

prefer configurable or relative paths where appropriate.

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)

Good security scripts often have:

INPUT
VALIDATION
PROCESSING
OUTPUT
ERROR HANDLING
LOGGING

Structure:

def main():
pass
if __name__ == "__main__":
main()

It creates a clear entry point.

Conceptually:

IMPORTS
FUNCTIONS
MAIN WORKFLOW
PROGRAM START

A mature script may look like:

CONFIGURATION
COLLECT DATA
VALIDATE
NORMALIZE
ANALYZE
ENRICH
SCORE
REPORT

Different tools may represent severity as:

HIGH
High
high
4
critical

Normalize before analysis.

Example:

severity = severity.strip().lower()

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 RESPONSE

without appropriate controls.

Prefer:

ALERT
COLLECT CONTEXT
SCORE
ANALYST REVIEW
APPROVED RESPONSE

for high-impact actions.

Build a script that:

Reads a Log File
Finds Failed Logins
Counts Failures by User
Counts Failures by IP
Assigns Risk
Generates Report
AUTH LOG
READ
PARSE
COUNT
ANALYZE
REPORT

Build:

INPUT FILE
SHA-256
OUTPUT HASH
SAVE REPORT

Features:

File Existence Check
SHA-256
Timestamp
Readable Output
Error Handling

Input:

IOC LIST

Process:

Read
Normalize
Remove Duplicates
Validate
Sort

Output:

Clean IOC List

93 — Project 04: Vulnerability Report Parser

Section titled “93 — Project 04: Vulnerability Report Parser”

Input:

CSV VULNERABILITY EXPORT

Process:

Read CSV
Filter High / Critical
Group by Asset
Count Findings
Prioritize

Output:

Security Summary

In an authorized training API:

API
AUTHENTICATE
COLLECT EVENTS
PARSE JSON
FILTER
REPORT

Ensure credentials are stored securely.

95 — Project 06: Asset Inventory Analyzer

Section titled “95 — Project 06: Asset Inventory Analyzer”

Input:

Asset CSV / JSON

Analyze:

Hostname
IP
OS
Owner
Criticality
Environment

Identify:

Missing Owners
Unknown Criticality
Duplicate Assets
Incomplete Records

96 — 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 SUMMARY

97 — 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 Events

Python can:

Parse
Filter
Compare
Report

Focus on:

Log Parsing
Alert Enrichment
IOC Processing
API Integration
CSV / JSON
Report Generation

Focus on authorized workflows such as:

Result Parsing
Data Organization
Evidence Processing
Asset Analysis
API Interaction
Report Automation

The 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 Checks

Focus on:

Evidence Parsing
Hashing
Timeline Processing
Log Analysis
IOC Correlation
Report Generation

Focus on:

Large Log Sets
Indicators
Event Correlation
Baselines
Anomaly Summaries
Threat Intelligence

Focus on:

API Data
Source Analysis Support
Dependency Data
Security Test Results
Reporting
Security Automation

Use:

READ
TYPE
RUN
MODIFY
BREAK
DEBUG
APPLY

Do not simply copy and paste examples.

Change them.

When something fails:

READ ERROR MESSAGE
IDENTIFY ERROR TYPE
IDENTIFY LINE
CHECK INPUT
CHECK DATA TYPE
CHECK ASSUMPTION
FIX
RUN AGAIN

Expect:

SyntaxError
NameError
TypeError
ValueError
KeyError
FileNotFoundError
ModuleNotFoundError

Learning to interpret these errors is a core programming skill.

This fails if the key does not exist:

event = {
"user": "analyst01"
}
print(event["severity"])

Safer:

print(event.get("severity", "unknown"))

Input returns a string:

count = input("Enter failed login count: ")

Convert:

count = int(count)

with appropriate exception handling.

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?

Every portfolio script should include:

Project Name:
Security Problem:
Purpose:
Requirements:
Input:
Output:
How to Run:
Security Considerations:
Limitations:
Example:

Example:

# Failed Login Analyzer
## Purpose
## Requirements
## Input Format
## Usage
## Output
## Security Considerations
## Limitations

Test:

VALID INPUT
EMPTY INPUT
INVALID INPUT
MISSING FILE
MALFORMED JSON
API TIMEOUT
NO RESULTS
LARGE INPUT

Use:

WRITE
TEST
REVIEW
FIX
DOCUMENT
COMMIT

Before pushing code, check for:

API Keys
Passwords
Tokens
Private Keys
Internal URLs
Sensitive Data

Sensitive or local files may belong in:

.gitignore

Examples might include:

.env
.venv/
__pycache__/
local-results/
sensitive-data/

depending on the project.

You understand:

Variables
Strings
Numbers
Conditions
Loops

You understand:

Lists
Dictionaries
Sets
Functions

You can process:

Logs
CSV
JSON

You can:

Parse
Filter
Count
Group
Normalize

You can:

Call APIs
Authenticate Safely
Parse Responses
Handle Errors

You can:

Collect
Analyze
Enrich
Score
Report

You can create reusable:

Log Analyzers
IOC Utilities
Asset Tools
Reporting Tools
API Collectors
Week Focus
1 Variables, Conditions, Loops, Functions
2 Files, Logs, CSV, JSON
3 Regex, Hashing, APIs, Error Handling
4 Security Automation Project

Spend your practice time roughly like:

20%
READ CONCEPT
30%
TYPE EXAMPLES
50%
SOLVE SECURITY PROBLEM

The goal is to use Python, not memorize Python.

  • Python installed
  • Scripts can be executed
  • Variables understood
  • Data types understood
  • Conditions understood
  • Loops understood
  • Functions understood
  • Lists
  • Dictionaries
  • Sets
  • Tuples
  • Nested data
  • Read text files
  • Write files
  • Process line by line
  • Handle missing files
  • Work with paths
  • 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
  • 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
  • Validate input
  • Avoid hard-coded secrets
  • Use least privilege
  • Handle errors
  • Protect logs
  • Review dependencies
  • Avoid unsafe shell construction
  • 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”
  1. Why is Python useful in cybersecurity?
  2. What is a variable?
  3. What is a string?
  4. What is an integer?
  5. What is a boolean?
  6. What is a list?
  7. What is a dictionary?
  8. Why are dictionaries important when working with APIs?
  9. What is a set?
  10. When are sets useful for security data?
  11. What is a loop?
  12. What does a condition do?
  13. What is a function?
  14. Why should large scripts be separated into functions?
  15. What does return do?
  16. Why is with open() useful?
  17. Why should large log files often be processed line by line?
  18. What is exception handling?
  19. Why should specific exceptions be preferred?
  20. What is a Python module?
  21. What does hashlib provide?
  22. What is SHA-256 used for?
  23. What does the ipaddress module provide?
  24. What is a regular expression?
  25. When should regex not replace proper data validation?
  26. What is CSV?
  27. What is JSON?
  28. How does JSON map to Python dictionaries and lists?
  29. Why are timestamps important in security investigations?
  30. Why is structured logging useful?
  31. What is an API?
  32. Why should API requests use timeouts?
  33. Why should API credentials not be hard-coded?
  34. What are environment variables?
  35. What is a virtual environment?
  36. Why should external Python packages be reviewed before installation?
  37. Why can shell=True be dangerous with untrusted input?
  38. Why should security automation run with least privilege?
  39. Why should scripts be tested with invalid inputs?
  40. 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
REPORT

Do not think:

I MUST MEMORIZE
ALL OF PYTHON

Think:

I NEED TO UNDERSTAND
THE SECURITY PROBLEM
BREAK IT INTO
SMALL LOGICAL STEPS
USE PYTHON
TO AUTOMATE THOSE STEPS

For example:

LOG FILE
READ
FILTER
COUNT
RISK
REPORT

or:

SECURITY API
REQUEST
JSON
PARSE
FILTER
SECURITY RESULT

or:

VULNERABILITY CSV
READ
FILTER HIGH RISK
GROUP BY ASSET
PRIORITIZE
REPORT

That is Python for cybersecurity.

➡️ 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 AUTOMATION

The 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.