Skip to main content
Ethical hacking / Article

Learn Python for Security: A Log-Analysis Exercise

Build a Python 3 log-analysis script with fictional CSV data, input validation, expected results, and clear limits on what the evidence proves.

Start reading
Learn Python for Security: A Log-Analysis Exercise

Python is useful in security work when it turns a repetitive question into a small, inspectable program. Start with something you can verify: read a log, count events, and explain the result. A script that produces a number without handling bad input or describing its assumptions is not yet a reliable investigation tool.

Set up an isolated Python 3 project

Use a supported Python 3 installation. Python 2 is obsolete; older tutorials that recommend its package ecosystem should not define a new setup. Check Python's download page for your operating system, then confirm the executable you installed.

python3 --version
mkdir security-notes
cd security-notes
python3 -m venv .venv
source .venv/bin/activate
python --version

On Windows, use py -3 -m venv .venv if you installed the Python launcher. In Command Prompt, activate with .venv\Scripts\activate.bat. The official virtual-environment guide explains the platform differences. The exercise below needs only the standard library, so there is nothing to download from a package index.

Use a tiny dataset you understand

Create events.csv with this fictional data. The addresses belong to documentation ranges; these rows are a local exercise, not a record of a real incident.

time,user,source_ip,result
09:14:00,alex,192.0.2.10,failed
09:14:10,alex,192.0.2.10,failed
09:14:30,alex,192.0.2.10,success
09:15:00,blair,198.51.100.8,failed

Before writing code, count the failed events by hand. You should get two for Alex's source and one for Blair's. This gives you an expected answer that is independent of the implementation. Write that answer in your notes; it becomes the first check of your script.

Read, validate, then count

import csv
from collections import Counter
from ipaddress import ip_address
from pathlib import Path

failures = Counter()
invalid = 0
path = Path("events.csv")

with path.open(encoding="utf-8", newline="") as handle:
    rows = csv.DictReader(handle)
    required = {"time", "user", "source_ip", "result"}
    if not required.issubset(rows.fieldnames or []):
        raise ValueError("Missing required CSV columns")
    for row in rows:
        result = (row.get("result") or "").strip().lower()
        source = (row.get("source_ip") or "").strip()
        try:
            source = str(ip_address(source))
        except ValueError:
            invalid += 1
            continue
        if result not in {"failed", "success"}:
            invalid += 1
            continue
        if result == "failed":
            failures[source] += 1

for source, count in sorted(failures.items()):
    print(f"{source}: {count} failed event(s)")
print(f"Invalid rows: {invalid}")

Save this as count_failures.py and run python count_failures.py from the project directory. The CSV reader handles fields and delimiters; it is more appropriate than splitting every line on commas. The validation steps make malformed input visible instead of quietly mixing it into the result.

Check the failure cases

Add a row with not-an-ip as its source. The invalid count should increase and the valid counts should stay unchanged. Next, remove the result header. The script should stop with a clear error rather than printing an empty report that looks successful. Restore the file and try an input with only the header: zero failed events is then a legitimate result.

These checks teach a more useful habit than adding features immediately. For every assumption—column names, input encoding, allowed result values—decide whether a violation should stop the program or be reported as a skipped record. Silent errors are especially troublesome when a human will use your output to make a security decision.

Separate the count from the conclusion

Two failed events followed by a success do not prove an account takeover. A person may have mistyped a password. Several users may share a source address behind a gateway. The exercise establishes a count for this input file; it does not establish intent, device identity, or the state of the real account.

A useful note says: “The sample contains two failed events from 192.0.2.10 and one subsequent success for Alex. I would check whether the session and device are expected.” That identifies the observation and the next question without inventing a verdict.

Expand in small, testable steps

First accept a file path as an argument with argparse. Then write a CSV summary using csv.DictWriter. After that, parse complete timestamps and define an explicit time window. For each change, add a tiny input and an expected output. Keep the original sample so you can detect a regression.

When you eventually need third-party packages, review the project, its installation instructions, and its supported Python versions. Install dependencies into the virtual environment and record them for reproducibility. Avoid copying credentials into scripts or uploading real logs to public repositories.

The CSV documentation and IP address documentation explain the APIs used here. For the investigation side, continue with SOC investigation notes and turn the script's output into a short, evidence-based case record.

Related Articles

COMMENTS (0)

Sign in to post intel on this briefing.

NEW350+ rooms now have a live terminal, so you can learn by typing the commands, right in your browser.Learn in a live terminal. 350+ rooms.Try a labCodelivly is 100% free, no paywall. If it helped you, chip in to keep it running.100% free. Help keep it so.Support us
CodelivlyRESOURCES

BLACK
FRIDAY.

70%OFF
70% off paid ebooks and playbooks.
Rooms, paths and labs stay free.
Limited time offer
Get 70% off (opens in a new tab)