01 / 20

Log Parsing
Scripts

Learn to write simple scripts that parse log files and extract indicators of compromise to defend networks and investigate incidents.

Cyber Security

What Are Log Files?

Every system, application, and network device generates log files: timestamped records of events that happen during operation. They are the digital breadcrumbs that tell us what happened, when, and to whom.

System Logs
OS events: logins, errors, service starts/stops
Web Server Logs
HTTP requests: IP, URL path, status codes, user agent
Firewall Logs
Network traffic: allowed/blocked connections, ports, protocols

Anatomy of a Log Line

192.168.1.105 - - [17/Jun/2025:09:14:32 +0000] "GET /admin/login.php HTTP/1.1" 200 4523
IP Address
Who made the request: the source identifier
Timestamp
When it happened: date, time, timezone
Request Path
What was accessed: the resource URL
Status Code
The result: 200 OK, 404 Not Found, 403 Forbidden

Indicators of Compromise (IOCs)

An Indicator of Compromise (IOC) is any observable artifact in a log that suggests a system may have been breached or attacked. Parsing scripts search for these patterns automatically.

Suspicious IPs
Known malicious addresses or unexpected geolocations
Failed Logins
Repeated 401/403 codes indicating brute-force attempts
Unusual Paths
Requests to /etc/passwd, /wp-admin, or SQL injection strings

The Log Parsing Pipeline

READ Open file, iterate lines PARSE Split fields, extract values FILTER Match patterns, check conditions REPORT Output results, alert / save

Core Technique: String Splitting

The simplest parsing approach: split each line by a delimiter (space, comma, tab) to extract individual fields. This works well for structured logs with consistent formatting.

# Python: split a log line by spaces line = "192.168.1.105 - - [17/Jun/2025:09:14:32] GET /admin 200" fields = line.split(" ") ip_address = fields[0] # "192.168.1.105" http_method = fields[4] # "GET" path = fields[5] # "/admin" status_code = fields[6] # "200"

Pattern Matching with Regex

When log formats are complex or inconsistent, regular expressions (regex) let you define precise patterns to search for. Think of regex as a search template with wildcards.

# Python: extract all IP addresses from a log file import re pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" with open("access.log") as f: for line in f: ips = re.findall(pattern, line) if ips: print(ips)

Splitting vs Regex

String Splitting Regular Expressions
Complexity Simple, beginner-friendly Steeper learning curve
Best For Consistent delimiters (CSV, TSV) Complex, variable formats
Flexibility Limited: breaks if format changes High: handles variations
Performance Faster on simple data Slightly slower, more powerful
Example Use CSV logs, syslog IP extraction, timestamp parsing

How to Write a Parsing Script

1
Identify the log format. Read a few sample lines and note the delimiter, field order, and any quirks.
2
Open and read the file. Use a loop to process one line at a time to handle large files without running out of memory.
3
Parse each line. Use split() for clean data or regex for complex patterns to extract fields like IP, timestamp, and status code.
4
Apply filters. Check extracted fields against your IOC criteria: known bad IPs, error codes, suspicious paths.
5
Output the results. Print to console, write to a file, or feed into a SIEM (Security Information and Event Management) system.

Example 1: Count Requests Per IP

Goal: find which IP addresses are making the most requests. A high request count from a single IP may indicate automated scanning or a denial-of-service attempt.

# Count requests per IP address ip_counts = {} with open("access.log") as f: for line in f: ip = line.split()[0] ip_counts[ip] = ip_counts.get(ip, 0) + 1 # Print top offenders for ip, count in sorted(ip_counts.items(), key=lambda x: x[1], reverse=True)[:5]: print(ip, count)

Example 2: Detect Failed Logins

Goal: flag IPs with repeated 401 (Unauthorized) responses. More than 10 failures from one IP strongly suggests a brute-force attack.

# Detect brute-force login attempts failed = {} THRESHOLD = 10 with open("access.log") as f: for line in f: # Split by quote to isolate the request string parts = line.split('"') if len(parts) < 3: continue # Skip malformed lines ip = parts[0].strip().split()[0] # Status code is after the request string status = parts[2].strip().split()[0] if status == "401": failed[ip] = failed.get(ip, 0) + 1 for ip, count in failed.items(): if count > THRESHOLD: print(f"ALERT: {ip} has {count} failed logins")

Example 3: Extract IOCs with Regex

Goal: find all requests containing SQL injection patterns like UNION SELECT, OR 1=1, or single-quote characters in the URL path.

import re # Patterns that indicate SQL injection attempts sqli_pattern = re.compile( r"(union\s+select|or\s+1\s*=\s*1|'|--|\bselect\b.*\bfrom\b)", re.IGNORECASE ) with open("access.log") as f: for num, line in enumerate(f, 1): if sqli_pattern.search(line): print(f"Line {num}: {line.strip()}")

Combining Techniques

Log File split() per line Extract Fields regex: IP pattern Find all IPs filter: status == 401 Failed logins regex: SQLi patterns Injection attempts REPORT Alerts + Summary

Key Data Structures

Choosing the right data structure determines how efficiently your script aggregates and searches through log data.

Dictionary
Key-value pairs for counting (IP counts, error tallies). Lookup time: \( O(1) \) average.
Set
Unique collection for tracking distinct IPs or paths seen. No duplicates, fast membership check.
List
Ordered collection for storing matching lines, building timelines, or preserving log order.

Common Mistakes

✕ Loading Entire File Into Memory
Reading all lines at once with readlines() crashes on large logs. Process one line at a time using a for loop.
✕ Hardcoding Field Positions
Assuming the IP is always field[0] without checking. Different log formats place fields in different positions.
✕ Ignoring Encoding Errors
Logs may contain non-UTF-8 characters. Always open files with errors="ignore" or "replace" as a safety net.

Parsing Techniques Summary

Technique When to Use IOC Examples
split() Clean, consistent delimiters IP counts, status codes
regex findall() Extract specific patterns IP addresses, email addresses
regex search() Detect presence of a pattern SQLi strings, XSS payloads
Dictionary counting Aggregate and threshold Brute-force detection
Set membership Compare against known-bad list Threat intel IP matching

Question 1 of 5

Which Python method is best suited for breaking a log line into individual fields when the format uses a consistent space delimiter?

Question 2 of 5

A security analyst finds that IP 10.0.5.22 has generated 847 requests in the last hour while all other IPs average 12. What type of IOC does this most likely indicate?

Question 3 of 5

In the following code, what does ip_counts.get(ip, 0) return if the IP has never been seen before?

Question 4 of 5

Why is it a common mistake to use readlines() to load an entire log file at once?

Question 5 of 5

A parsing script uses the regex pattern \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}. What does this pattern match?