Automate Cybersecurity Tasks with Python
Data types and structures
Core types are str, int, float, and bool; convert with str(), int(), and float(). Lists are ordered and mutable and index from 0; tuples are immutable; dictionaries store key-value pairs and are looked up by key, not position.
Control flow and functions
if / elif / else branch; for iterates over an iterable while while repeats on a condition. Functions defined with def take parameters and return values, and variables inside them are locally scoped. Built-ins worth knowing: print(), type(), len(), range(), sorted(), max(), min(), sum(). String methods include .upper(), .lower(), .split(), .join(), .replace(), and .index(); list methods include .append(), .insert(), .remove(), and .index().
Files and regular expressions
Open files with with open('file.txt', 'r') as f: so they close automatically, then use .read() or .readlines(); .write() writes. The re module does pattern matching: re.findall(pattern, string) returns a list of every match, re.search() returns the first match object, re.split() splits on a pattern. Know classes (\w, \d, \s), quantifiers (*, +, ?), anchors (^, $), and escaping.
Traps
Strings are immutable - methods return new strings rather than changing the original. .index() raises an error when the value is missing, so check membership with in first. .sort() mutates a list while sorted() returns a new one. and binds tighter than or, and comparing an int to a str silently yields False. Most automation bugs in exams are off-by-one index errors.
Rule of thumb
When parsing a log line, split on the delimiter, then check len() of the resulting list before indexing the field you need.