UnixDroid

Lesson 12 of 12 · 9 min

Capstone: build a brute-force detector for auth logs

Flip from attacker to defender. Build a script that reads a login log and flags the IPs hammering it with failed passwords.

You've spent this path building attacker tools. Now flip to defence. In this capstone you'll write a brute-force detector — a script that reads a server's login log and spots the IP addresses hammering it with failed passwords. This is real blue-team work, and it ties together everything you've learned.

The idea

A brute-force attack means many failed logins from one source in a short time. The log records every attempt — so detection is just counting failures per IP and flagging anyone over a threshold.

Reading the log

Linux records SSH logins in /var/log/auth.log. A failed attempt is a line containing Failed password ... from <IP>.

import re
from collections import Counter

fails = Counter()

with open('auth.log') as f:
    for line in f:
        if 'Failed password' in line:
            match = re.search(r'from (\\d+\\.\\d+\\.\\d+\\.\\d+)', line)
            if match:
                fails[match.group(1)] += 1

Counter tallies failures per IP automatically — no manual bookkeeping.

Flagging the attackers

THRESHOLD = 10

for ip, count in fails.most_common():
    if count >= THRESHOLD:
        print(f'[!] {ip} — {count} failed logins (possible brute force)')
TechniqueLesson it came from
Reading a file line by lineFiles and functions
Regex to extract an IPOSINT scraping
Counter to tallyPython basics
A threshold decisionConditionals

Tip: Real tools (like fail2ban) do exactly this, then act — blocking the IP in the firewall automatically. A good next step is to have your script write offending IPs to a file or alert you, rather than just print them. Tune the threshold to your traffic: too low and you flag yourself fat-fingering a password; too high and you miss a slow attack.

You've come full circle

You started by learning why attackers love Python and end by using it to catch them. That's the whole point of ethical hacking: you learn the offence so you can build the defence. Take this detector, improve it, and you've got a genuine portfolio project.

Try it yourself
  1. Create a fake auth.log with a few 'Failed password ... from 1.2.3.4' lines.
  2. Run the detector and confirm it counts them.
  3. Lower the threshold to 3 and add a second attacker IP to the log.
No Linux machine? Practise in the free online terminal

Quick check

Which Python object from collections automatically tallies how many times each item (like an IP) appears?

Need a hint?

It 'counts' for you.

Finished this lesson?

Done lessons keep your daily streak going 🔥

0 day streak

0 lessons done

best 0 days

Log in to keep your streak on every device →