Python › Module 3 › Lesson 3
Log Parser Script
Parse text logs line-by-line to count errors, failed logins, or suspicious IPs
Opening
grep is great—scripts scale better
Manual searches find one incident. Parsers tally failures across days, group by IP, and write a short report. Start with substring filters; add regex when patterns get messy.
1. Count Matching Lines
Count failed passwordsfrom collections import Counter path = "sample_auth.log" needle = "Failed password" count = 0 with open(path, encoding="utf-8", errors="ignore") as f: for line in f: if needle in line: count += 1 print("failures:", count)
from collections import Counter
path = "sample_auth.log"
needle = "Failed password"
count = 0
with open(path, encoding="utf-8", errors="ignore") as f:
for line in f:
if needle in line:
count += 1
print("failures:", count)2. Group by Something Useful
Next step (lab): extract source IPs and Counter them. Top talkers often reveal password spraying. Always work on exported log copies, not live production files you might lock or corrupt.
Copy → parse → report
Never experiment parsers against the only copy of a log. Duplicate first.
Knowledge Check
A log parser commonly:
Multiple choice
Knowledge Check
True or False: Counting failed logins by IP can highlight spraying.
True or False
Knowledge Check
Best practice before parsing?
Multiple choice