Automation June 2025 9 min read

Automating Threat Detection with Python

A practical guide to writing Python scripts that integrate with SIEM APIs, enrich IOCs automatically, suppress duplicate alerts, and send formatted notifications — turning manual triage into scalable automation.

Published
Author: Sid Faza Category: Automation
// 01

Why Automate Threat Detection?

The average SOC analyst handles between 200 and 1,000 alerts per day. At that volume, manual investigation of every alert is not just impractical — it's impossible. Automation is not about replacing analysts. It is about freeing analysts to do the work only humans can do while computers handle the repetitive mechanics.

Automation should handle the first 80% of alert processing — collection, enrichment, deduplication, and routing. Humans handle the final 20% that requires judgment.

Python is the ideal language for SOC automation: it has mature libraries for every API you'll encounter, a short feedback loop for scripting, and is readable enough that non-developers can understand and contribute to playbooks.

// 02

Connecting to SIEM APIs

Splunk REST API
python — Splunk Search API
import splunklib.client as client
import splunklib.results as results

service = client.connect(
    host=splunk.internal, port=8089,
    username=svc_soc, password=SPLUNK_PASS)

query = 'search index=security severity=critical | head 100'
job = service.jobs.create(query, exec_mode=blocking)
for result in results.JSONResultsReader(job.results()):
    print(result)
Wazuh API
python — Wazuh REST API
import requests

token = requests.post(https://wazuh.internal:55000/security/user/authenticate,
    auth=(wazuh_user, PASSWORD), verify=False).json()[data][token]

headers = {Authorization: f'Bearer {{token}}' }
alerts = requests.get(https://wazuh.internal:55000/alerts?limit=100&level=12,
    headers=headers, verify=False).json()
// 03

IOC Enrichment Automation

python — Multi-Source Enrichment
import requests, functools

@functools.lru_cache(maxsize=512)
def enrich(ioc: str, kind: str) -> dict:
    if kind == ip:
        r = requests.get(
          f'https://www.virustotal.com/api/v3/ip_addresses/{{ioc}}' ,
          headers={x-apikey: VT_KEY}).json()
        stats = r[data][attributes][last_analysis_stats]
        return {malicious: stats[malicious],
                country:   r[data][attributes].get(country,?)}
    elif kind == hash:
        r = requests.get(
          f'https://www.virustotal.com/api/v3/files/{{ioc}}' ,
          headers={x-apikey: VT_KEY}).json()
        return {malicious: r[data][attributes][last_analysis_stats][malicious]}
// 04

Alert Deduplication

Without deduplication, the same event can fire the same alert dozens of times within minutes. Dedup reduces noise, improves analyst focus, and prevents on-call fatigue.

python — Redis-Based Dedup
import redis, hashlib, json

r = redis.Redis(host=localhost, port=6379)

def is_duplicate(alert: dict, window_seconds: int = 3600) -> bool:
    key_fields = [alert.get(rule_id), alert.get(src_ip), alert.get(dest_ip)]
    key = hashlib.md5(json.dumps(key_fields).encode()).hexdigest()
    if r.exists(key):
        return True  # Already seen in this window
    r.setex(key, window_seconds, 1)
    return False
// 05

Notification Engine

python — Slack Block Kit Dispatcher
from slack_sdk import WebClient

slack = WebClient(token=SLACK_TOKEN)

def notify(alert: dict):
    colour = {critical: 🔴, high: 🟠, medium: 🟡}
    icon = colour.get(alert[severity], ⚪)
    blocks = [
      {type: header, text: {
          type: plain_text,
          text: f'{{icon}} {{alert[severity].upper()}}: {{alert[title]}}' }},
      {type: section, fields: [
          {type: mrkdwn, text: f'*Host:* {{alert[hostname]}}' },
          {type: mrkdwn, text: f'*VT:* {{alert[vt_score]}}/70 malicious' },
          {type: mrkdwn, text: f'*Country:* {{alert[country]}}' },
          {type: mrkdwn, text: f'*Rule:* {{alert[rule_id]}}' }
      ]}
    ]
    slack.chat_postMessage(channel=#soc-alerts, blocks=blocks)
// 06

Full Pipeline Walkthrough

SIEM Query
Every 5 min
→
Parse Alerts
JSON normalise
→
Dedup Check
Redis cache
→
Enrich IOCs
VT + AbuseIPDB
→
Score & Route
Severity matrix
→
Notify
Slack + Email
→
Ticket
Jira auto-create
Result

Implementing this pipeline across a 1,200-alert/day environment reduced analyst triage time from 4.5 hours/day to under 1 hour/day — a 73% reduction in MTTR.