Chapter 6: Security Automation & Incident Response

Develop Python scripts for incident handling, alert generation, IOC detection and cyber security automation.

Incident ResponseIOC DetectionAlert GenerationPython AutomationTriage
Detect
Indicators
Generate
Alerts
Triage
Incidents
Create
Reports

6.1 Chapter Overview

Security automation helps cyber security teams respond faster and more consistently. Instead of manually reviewing every log line, checking every IP address, or writing every report from scratch, Python scripts can assist with triage, alert generation, IOC detection and incident documentation.

Incident response is the structured process of identifying, containing, investigating and recovering from cyber security incidents. Python supports this process by automating repetitive tasks while analysts focus on decision-making and investigation.

Learning Outcome: By the end of this chapter, learners should be able to develop Python scripts for incident handling, alert generation, IOC detection and basic cyber security automation.
Logs / Alerts
Python Automation
IOC Matching
Triage Result
Incident Report

6.2 Learning Objectives

  • Understand the incident response lifecycle.
  • Explain what IOCs are and how they support detection.
  • Create Python scripts to check IPs, domains, hashes and log indicators.
  • Generate alerts based on detection rules.
  • Perform basic incident triage using severity scoring.
  • Create automated incident reports in CSV and text format.
  • Use Python to support containment recommendations.
  • Understand safe and authorized use of security automation.

6.3 Incident Response Lifecycle

Incident response follows a structured process to manage security incidents effectively.

1Preparation
2Identification
3Containment
4Eradication
5Recovery
6Lessons Learned
StageMeaningPython Automation Example
PreparationPrepare tools, scripts, playbooks and contacts.Create IOC lists and log parsers.
IdentificationDetect suspicious activity.Match logs against known malicious IPs.
ContainmentLimit impact of incident.Generate block-list recommendations.
EradicationRemove threat from environment.List suspicious files for cleanup review.
RecoveryRestore systems safely.Validate services and logs after recovery.
Lessons LearnedImprove future defenses.Generate incident summary report.

6.4 Indicators of Compromise

An Indicator of Compromise, or IOC, is evidence that may suggest malicious activity. IOCs help analysts detect and investigate incidents.

IOC TypeExampleSecurity Use
IP Address203.0.113.5Detect suspicious source or destination.
Domainmalicious-example.comDetect phishing or command-and-control communication.
File HashSHA256 hash valueIdentify known malicious files.
File Nameinvoice_payload.exeDetect suspicious attachments.
URLhttp://bad.example/loginDetect phishing or malware delivery links.
User BehaviorRepeated failed loginDetect brute force or account compromise.

Python IOC List Example

malicious_ips = ["203.0.113.5", "198.51.100.77"]
malicious_domains = ["malicious-example.com", "phishing-test.net"]
malicious_files = ["payload.exe", "invoice_malware.docm"]

print("Loaded IOC lists successfully")

6.5 IOC Matching in Logs

This script checks log lines against known malicious IP indicators.

Create Sample Log File

log_data = """2026-06-02 10:01 user=amin action=login_success ip=192.168.1.10
2026-06-02 10:02 user=admin action=login_failed ip=203.0.113.5
2026-06-02 10:03 action=outbound_connection domain=malicious-example.com
2026-06-02 10:04 user=guest action=download file=invoice_malware.docm
"""

with open("incident_logs.txt", "w", encoding="utf-8") as file:
    file.write(log_data)

print("Sample incident log created.")

Detect IOCs

malicious_ips = ["203.0.113.5", "198.51.100.77"]
malicious_domains = ["malicious-example.com", "phishing-test.net"]
malicious_files = ["payload.exe", "invoice_malware.docm"]

with open("incident_logs.txt", "r", encoding="utf-8") as file:
    for line in file:
        for ip in malicious_ips:
            if ip in line:
                print("ALERT: Malicious IP detected:", ip)
                print(line.strip())

        for domain in malicious_domains:
            if domain in line:
                print("ALERT: Malicious domain detected:", domain)
                print(line.strip())

        for file_name in malicious_files:
            if file_name in line:
                print("ALERT: Malicious file detected:", file_name)
                print(line.strip())

6.6 Alert Generation with Python

An alert is a notification that a suspicious condition has been detected. Alerts should include clear information such as time, source, indicator, severity and recommended action.

from datetime import datetime

def generate_alert(alert_type, indicator, severity, recommendation):
    alert = {
        "time": str(datetime.now()),
        "type": alert_type,
        "indicator": indicator,
        "severity": severity,
        "recommendation": recommendation
    }

    return alert

alert = generate_alert(
    "Malicious IP",
    "203.0.113.5",
    "High",
    "Review logs and consider blocking the IP if confirmed malicious."
)

print(alert)

Save Alerts to CSV

import csv
from datetime import datetime

alerts = [
    ["time", "type", "indicator", "severity", "recommendation"],
    [datetime.now(), "Malicious IP", "203.0.113.5", "High", "Investigate source IP"],
    [datetime.now(), "Suspicious File", "invoice_malware.docm", "Critical", "Isolate host and collect evidence"]
]

with open("security_alerts.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(alerts)

print("Alert CSV created.")

6.7 Incident Triage and Severity Scoring

Triage is the process of quickly assessing an alert to decide priority and next steps.

FactorLowMediumHigh
Asset CriticalityTest machineDepartment serverDomain controller or finance server
Indicator ConfidenceUnknownSuspiciousConfirmed malicious
ImpactNo impactLimited disruptionData loss or active compromise
SpreadSingle eventMultiple attemptsMultiple systems affected

Python Severity Scoring Example

def calculate_severity(asset_criticality, indicator_confidence, spread):
    score = 0

    if asset_criticality == "high":
        score += 3
    elif asset_criticality == "medium":
        score += 2
    else:
        score += 1

    if indicator_confidence == "confirmed":
        score += 3
    elif indicator_confidence == "suspicious":
        score += 2
    else:
        score += 1

    if spread == "multiple_systems":
        score += 3
    elif spread == "multiple_attempts":
        score += 2
    else:
        score += 1

    if score >= 8:
        return "Critical"
    elif score >= 6:
        return "High"
    elif score >= 4:
        return "Medium"
    else:
        return "Low"

severity = calculate_severity("high", "confirmed", "multiple_attempts")

print("Incident Severity:", severity)

6.8 File Hash Checking

File hashes help identify known malicious files. A hash is like a fingerprint of a file.

Create SHA256 Hash of a File

import hashlib

file_path = "sample_file.txt"

with open(file_path, "w", encoding="utf-8") as file:
    file.write("PDTC cyber security sample file")

sha256 = hashlib.sha256()

with open(file_path, "rb") as file:
    for block in iter(lambda: file.read(4096), b""):
        sha256.update(block)

print("SHA256:", sha256.hexdigest())

Compare File Hash with IOC List

known_bad_hashes = [
    "bad_hash_example_123",
    "another_bad_hash_456"
]

calculated_hash = "bad_hash_example_123"

if calculated_hash in known_bad_hashes:
    print("ALERT: File hash matches known malicious IOC")
else:
    print("File hash not found in known bad list")

6.9 Automated Containment Recommendation

Automation should not blindly take destructive action. In many environments, scripts should recommend containment actions for human approval.

def containment_recommendation(alert_type, severity):
    if alert_type == "Malicious IP" and severity in ["High", "Critical"]:
        return "Recommend blocking IP at firewall after analyst confirmation."

    if alert_type == "Malicious File" and severity == "Critical":
        return "Recommend isolating host and collecting forensic evidence."

    if alert_type == "Failed Logins" and severity in ["Medium", "High"]:
        return "Recommend reviewing user account and enabling MFA."

    return "Monitor and collect more evidence."

print(containment_recommendation("Malicious File", "Critical"))
Important: Automated containment should follow organization policy. Human approval may be required before blocking, isolating or deleting.

6.10 Complete Mini Incident Automation Script

This script reads logs, checks IOCs, generates alerts and creates a CSV report.

import csv
from datetime import datetime

malicious_ips = ["203.0.113.5", "198.51.100.77"]
malicious_domains = ["malicious-example.com"]
malicious_files = ["invoice_malware.docm"]

alerts = []

with open("incident_logs.txt", "r", encoding="utf-8") as file:
    for line in file:
        for ip in malicious_ips:
            if ip in line:
                alerts.append([
                    datetime.now(),
                    "Malicious IP",
                    ip,
                    "High",
                    line.strip(),
                    "Investigate and consider firewall block."
                ])

        for domain in malicious_domains:
            if domain in line:
                alerts.append([
                    datetime.now(),
                    "Malicious Domain",
                    domain,
                    "High",
                    line.strip(),
                    "Review DNS logs and block if confirmed."
                ])

        for file_name in malicious_files:
            if file_name in line:
                alerts.append([
                    datetime.now(),
                    "Malicious File",
                    file_name,
                    "Critical",
                    line.strip(),
                    "Isolate endpoint and collect evidence."
                ])

with open("incident_alert_report.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerow(["Time", "Alert Type", "Indicator", "Severity", "Evidence", "Recommendation"])
    writer.writerows(alerts)

print("Total alerts generated:", len(alerts))
print("Report created: incident_alert_report.csv")

6.11 Incident Report Template using Python

An incident report summarizes what happened, what was detected and what actions are recommended.

from datetime import datetime

incident_id = "INC-2026-001"
title = "Malicious IOC Detected in Logs"
severity = "High"
summary = "Python automation detected a known malicious IP in authentication logs."
recommendation = "Review affected host, verify activity and consider blocking the IP."

report = f"""
Incident Report
================
Incident ID: {incident_id}
Date: {datetime.now()}
Title: {title}
Severity: {severity}

Summary:
{summary}

Recommended Action:
{recommendation}

Prepared by:
PDTC Security Automation Script
"""

with open("incident_report.txt", "w", encoding="utf-8") as file:
    file.write(report)

print("Incident report created.")

6.12 Playbooks and Automation

A playbook is a predefined response procedure for a specific type of incident. Automation can support playbooks by collecting data, generating alerts and preparing reports.

Incident TypePlaybook StepsPython Automation Support
Brute Force LoginReview failed logins, identify IP, check account, escalate.Count failed logins by IP and user.
Malicious FileCalculate hash, check IOC list, isolate host, preserve evidence.Hash file and compare with known bad hashes.
Suspicious DomainCheck DNS logs, identify hosts, block domain if confirmed.Search logs for domain and create host list.
Firewall Deny SpikeIdentify source IPs, destination ports, affected assets.Summarize firewall logs by source IP and port.

6.13 Interactive IOC Detection Demo

Paste log lines below. The demo checks for sample malicious IP, domain and file indicators.

Click Detect IOCs.

6.14 Practical Activities

Activity 1: IOC Matching

Create lists of malicious IPs, domains and file names. Search a sample log file for matching indicators.

Activity 2: Alert CSV

Generate a CSV file containing alert type, indicator, severity and recommendation.

Activity 3: Severity Scoring

Create a function that calculates incident severity based on asset criticality, confidence and spread.

Activity 4: File Hash Check

Create a SHA256 hash of a sample file and compare it with a known-bad hash list.

Mini Project

Build a mini incident automation script that reads logs, detects IOCs, generates alerts and creates an incident report.

6.15 Interactive Final Assessment Quiz

Each correct answer gives +1 mark. Each wrong answer gives -0.5 mark.

1. Security automation can help analysts respond faster and more consistently.

2. IOC stands for:

3. A malicious IP address can be treated as an IOC.

4. Which Python module can calculate SHA256 hashes?

5. Incident triage helps prioritize alerts.

6. A CSV file can store generated security alerts.

7. Automated containment should follow organization policy and approval requirements.

8. Incident response includes preparation, identification, containment, eradication, recovery and lessons learned.

9. A file hash is like a fingerprint of a file.

10. Security automation should be used only in authorized environments.

Your Score: 0

6.16 Chapter Summary

In this chapter, learners studied security automation and incident response using Python. They learned the incident response lifecycle, IOC detection, alert generation, severity scoring, file hash checking, containment recommendations and incident report generation.

Remember: Security automation supports analysts. It should improve speed, consistency and accuracy while still following authorization, policy and human oversight.