Lesson 14 · 55 minutes
Build a triage tool that turns logs into ranked alerts and a short report
- Join the parser, the rules and the triage of the course into one command-line tool
- Rank the alerts and write a file for machines and a short report for people
- Give the tool a clear exit code and a clear failure message, and prove that it is repeatable
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
For two weeks you ran the steps by hand. The team lead wants them as one command that the night shift can run on the logs of the night: "Logs in, ranked alerts out, a short report that I can read with my coffee. If something is urgent, the command must say so by its exit code, so that a scheduler can page the analyst. And if the logs are missing, it must say that loudly and not print an empty report." You have the pieces: logparse.py (lesson 2), rules.py (lesson 3) and triage.py (lesson 4). This lesson joins them.
Recall
Lesson 13: the first alert came three minutes before the login succeeded, and the analyst took it 13 minutes later. Which measure is that?
The time to react: from the first alert to the moment that an analyst takes it. It shows how long an alert waits for a person, and it is the number that a paging rule is meant to cut.
Lesson 3: why does a rule stay quiet for one window after an alert?
So that one burst of events gives one alert with a count and not dozens. Without the quiet window the analyst gets a flood and stops reading.
The idea
A pipeline is a chain of stages, where each stage reads the output of the one before.
- Logs → Parse: three Linux logs
- Parse → Detect: events, one clock
- rules.json → Detect: the rules (rules.py)
- Detect → Triage: alerts
- Context files → Triage: assets, staff
- Triage → ranked.csv: for machines
- Triage → summary.txt: for people
- Triage → Exit code: 0, 1 or 2
The tool covers the Linux log part of the course, lessons 2 to 4. Evidence, containment and the report (lessons 12 and 13) stay separate programs that you run on its input when a case starts. The new work is at the two ends. A tool that other people and other programs use needs five properties.
| Property | What it means here |
|---|---|
| One command | The inputs are options with defaults: the logs folder, the context folder, the year, the clock offset and the rules file. |
| No hidden state | The result depends on the inputs and nothing else, so the same inputs give the same result. |
| Two outputs | ranked.csv for machines, summary.txt for people. |
| A contract in the exit code | 0: nothing urgent. 1: at least one alert of priority 1. 2: the input cannot be read. |
| Honest failure | A message on the error stream, and no output file that looks like a good result. |
The ranking puts the most urgent alert first. The key is a tuple of four values, each in the order that you want: the priority (1 first), then the criticality of the host (high first), then the severity of the rule (high first), then the time. The program takes the criticality from assets.csv by host name.
Worked example
1. Save the tool
analyse.py imports the three modules of the course. New in it: argparse is the standard module for command-line options. add_argument("--logs", default="data") defines an option and its default value, and parse_args() reads what the user typed. Counter counts the priorities. main() returns the exit code and the last line, sys.exit(main()), gives it to the shell. The option --offset is the number of hours that the clock of the host runs ahead of UTC, and it may be negative.
analyse.py
"""analyse.py: logs in, ranked alerts out, with a short report.
python3 analyse.py [--logs data] [--context .] [--year 2026] [--offset 1] [--rules rules.json]
Exit code: 0 when no alert is urgent, 1 when at least one alert has priority 1, 2 when the logs cannot be read.
"""
import argparse
import csv
import json
import sys
from collections import Counter
from logparse import load, sources
from rules import run_rules
from triage import load_context, triage
SEVERITY = {"high": 3, "medium": 2, "low": 1}
def why(r):
"""One short reason for the verdict, in the words of the facts."""
f, a = r["facts"], r["alert"]
if f["change"]:
return f"approved change {f['change']['ticket']}"
if f["odd"]:
return f"login as {f['odd'][0]['user']} from an address that is not theirs"
if a["severity"] == "high":
return "rule severity is high"
return f["known"] or "no success seen"
def main():
ap = argparse.ArgumentParser(description="Triage the logs of one host.")
ap.add_argument("--logs", default="data")
ap.add_argument("--context", default=".")
ap.add_argument("--year", type=int, default=2026)
ap.add_argument("--offset", type=int, default=1, help="hours that the clock of the host runs ahead of UTC")
ap.add_argument("--rules", default="rules.json")
args = ap.parse_args()
try:
events, bad = load(args.logs, args.year, sources(args.offset))
ctx = load_context(args.context)
rules = json.load(open(args.rules))
except (OSError, ValueError) as err:
print("cannot read the input:", err, file=sys.stderr)
return 2
if not events:
print("no events read from", args.logs, file=sys.stderr)
return 2
records = triage(run_rules(events, rules), events, ctx)
crit = {row["host"]: int(row["criticality"]) for row in ctx["assets"].values()}
records.sort(key=lambda r: (r["priority"], -crit.get(r["alert"]["host"], 3), -SEVERITY[r["alert"]["severity"]],
r["alert"]["last"]))
with open("ranked.csv", "w", newline="") as out:
w = csv.writer(out)
w.writerow(["rank", "id", "priority", "verdict", "rule", "group", "host", "severity", "first", "last", "count"])
for n, r in enumerate(records, 1):
a = r["alert"]
w.writerow([n, a["id"], r["priority"], r["verdict"], a["rule"], a["group"], a["host"], a["severity"],
a["first"], a["last"], a["count"]])
levels = Counter(r["priority"] for r in records)
lines = [f"Read {len(events)} events from {args.logs}, {len(bad)} lines not read.",
f"Window: {events[0]['ts']} to {events[-1]['ts']}",
"Alerts: " + str(len(records)) + " (" + ", ".join(f"P{p} {levels[p]}" for p in sorted(levels)) + ")",
"Top alerts:"]
lines += [f" {n}. {r['alert']['id']} P{r['priority']} {r['alert']['rule']} {r['alert']['group']}: {why(r)}"
for n, r in enumerate(records[:3], 1)]
open("summary.txt", "w").write("\n".join(lines) + "\n")
print("\n".join(lines))
return 1 if levels[1] else 0
if __name__ == "__main__":
sys.exit(main())2. Run it on Friday
The defaults are the folders and files of this lab: data, the current folder as the context, the year 2026, an offset of 1 hour and rules.json. echo $? prints the exit code of the last command.
python3 analyse.py
echo "exit code $?"Read 1290 events from data, 3 lines not read.
Window: 2026-11-20T00:00:00Z to 2026-11-20T23:50:00Z
Alerts: 8 (P1 3, P2 2, P3 2, P4 1)
Top alerts:
1. A008 P1 R4 svc-update: rule severity is high
2. A006 P1 R1 203.0.113.50: login as mwebb from an address that is not theirs
3. A007 P1 R3 203.0.113.50: login as mwebb from an address that is not theirs
exit code 1The three most urgent alerts are the new account and the two alerts for the intruder. Read the files that the tool wrote.
head -n 4 ranked.csv | cut -c1-110
wc -l ranked.csvrank,id,priority,verdict,rule,group,host,severity,first,last,count
1,A008,1,"true positive, impact",R4,svc-update,web01,high,2026-11-20T13:04:22Z,2026-11-20T13:04:22Z,1
2,A006,1,"true positive, impact",R1,203.0.113.50,web01,medium,2026-11-20T12:55:04Z,2026-11-20T12:56:04Z,5
3,A007,1,"true positive, impact",R3,203.0.113.50,web01,medium,2026-11-20T13:03:51Z,2026-11-20T13:03:51Z,1
9 ranked.csvranked.csv has a header and one line for each of the eight alerts. A machine can read it, and so can a spreadsheet.
3. Make it fail on purpose
Point the tool at a folder that does not exist. The message goes to the error stream, and the exit code is 2.
python3 analyse.py --logs no-such-folder
echo "exit code $?"cannot read the input: [Errno 2] No such file or directory: 'no-such-folder/auth.log'
exit code 2The tool also returns 2 when the folder holds no events at all (for example three empty files), because an empty report is the quiet failure that the team lead forbids. A scheduler that sees 2 knows that the tool did not run. It does not take the silence for "no alerts". That distinction is the difference between a tool and a script that hopes.
4. Prove that it is repeatable
Run the tool twice and compare the hash of the output (lesson 12). If your tool has hidden state, such as the time of the run, the hashes differ.
python3 analyse.py > /dev/null; sha256sum ranked.csv | cut -c1-16
python3 analyse.py > /dev/null; sha256sum ranked.csv | cut -c1-1691785a0a71432e5c
91785a0a71432e5cThe same input gives the same file. This is what makes a result something that you can defend in a report, and it lets you test the tool: keep one input and the expected ranked.csv, and compare after every change.
5. Run it every morning
The course "Linux", Part 2, shows how to write a shell script (lesson 11) and how to run it on a schedule with cron (lesson 12). A script that runs this tool and reacts to the exit code is one if command. This lab does not install a schedule.
Your turn
Run the tool over the logs of day 2 with the context folder that you made in lesson 4 (--logs data2 --context day2). Read ranked.csv and summary.txt, and answer from your own output. Then ask yourself which of the eight alerts a human must read first, and whether the tool agrees.
Check yourself
Why does the tool return 2 for a missing folder and not 1?
Because 1 already means "there is something urgent". If both meant 1, a scheduler could not tell a good run with a finding from a run that failed, and a broken tool would page the analyst for the wrong reason, or worse, be mistaken for a quiet night.
The criticality of the host is in the sort key. What happens when the host is not in assets.csv?
The program uses 3, a middle value, so that an unknown host is neither ignored nor placed first. A better tool would also report the unknown host, because an asset that nobody lists is a finding by itself.
You change a rule and the numbers change. How do you know that the change is the one you wanted?
Keep a fixed input and the expected output. Run the tool before and after, and compare the two ranked.csv files line by line. The difference should be only the alerts that the change was meant to touch.
The summary says "3 lines not read". When is that a problem?
When the number grows. A steady number such as the two cut lines and the marker line of the lab is normal. A sudden jump means that a program changed its log format, and the parser is silently losing events.
Field notes
- Write tests for the tool. The standard module
unittestis enough: keep a small log with a known attack, run the pipeline on it, and assert the expected alerts. Run the tests before you change a rule or a parser. - Add the version of the rules file and the date of the context files to the summary, so that a reader of an old report knows what produced it.
- The tool reads the three Linux logs (
auth.log,syslogandaccess.log). The VPN log (lesson 2), Windows events (lesson 5), endpoint alerts (lesson 6) and tested Sigma rules (lessons 7 and 8) join it the same way: one parser for each source, one rule for each pattern. The scenario test uses lessons 5, 6 and 8 on their own. - Do not let the tool act. It ranks and reports. Blocking an address or disabling an account is a decision for a person, and a tool that does it automatically can lock out the company on one bad alert.
- Log the tool's own runs: when it ran, how many events it read, and how long it took. A SOC tool that fails without a trace is worse than none.
- When the data grows, the pipeline needs a database and a real log platform. The stages stay the same: parse, detect, enrich, rank, report. What you built here is a working model of them.