Lesson 03 · 40 minutes
Write a rule that sorts log lines into classes
- Choose between paths with if, elif and else
- Repeat work with for and while loops
- Write a function and use it to classify log lines
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your team lead wants an authentication log sorted into failed, accepted and other lines. Then the network team exports forty lines from the firewall and asks you for a quick risk picture: "How many connections did the firewall block, and how many of them aimed at a dangerous service?" A person could count forty lines. The real export has forty thousand, and tomorrow there will be a new one. So you write the rule once as a function, and a loop applies it to every line.
Recall
Lesson 2: what does line.split(" from ")[1].split()[0] return for "Failed password for root from 203.0.113.7 port 22 ssh2"?
203.0.113.7. The first split cuts the line at from and [1] takes the second piece, 203.0.113.7 port 22 ssh2. The second split() cuts that piece into words, and [0] takes the first word.
Lesson 1: a script crashes with a traceback. What exit code does the shell show in $?
A number other than 0. A crash with an uncaught error gives 1. A program that works gives 0. This lesson ends with a function that returns a value: do not confuse a return value with an exit code.
The idea
Lesson 2 showed that Python marks a block of code with indentation: four spaces after a line that ends with a colon. There are no braces. Here are the block tools in full.
| Tool | What it does |
|---|---|
if / elif / else | Runs the first block whose test is true. |
for x in group | Runs a block once for each item of the group. |
while test | Runs a block again and again while the test is true. |
def name(args): | Names a block so that you can run it with different values. |
return value | Ends the function and hands a value back. |
A function that has no return gives back None.
- Take next line → Classify it: call classify(line)
- Classify it → Count it: add one to that class
- Count it → Take next line: until the lines end
Worked example
1. Choose a path and repeat
Create flow.py in ~/krlab/python. These are the new words:
ifruns its block when the test is true.elif(else if) is tried when the tests above it were false, andelseruns when none was true.==tests equality. A single=stores a value, so do not mix them.for number in range(3)runs the block three times.range(3)makes the numbers 0, 1 and 2.whilerepeats its block as long as the test is true.tries += 1adds one totries.- A list comprehension builds a new list in one line: "
pfor eachpinportswhere the test is true".
flow.py
port = 22
if port == 22:
print("ssh")
elif port == 80:
print("http")
else:
print("unknown")
for number in range(3):
print("attempt", number)
tries = 0
while tries < 3:
tries += 1
print("try", tries)
ports = [22, 80, 443, 8080]
web = [p for p in ports if p in (80, 443, 8080)]
print(web)python3 flow.pyssh
attempt 0
attempt 1
attempt 2
try 1
try 2
try 3
[80, 443, 8080]Now change range(3) to range(5) and tries < 3 to tries < 5, and run the file again. A while loop needs something inside it that changes the test, or it never ends. If it does, press Ctrl+C. The parentheses (80, 443, 8080) make a tuple: a fixed group that you cannot change. Use a comprehension when it fits on one short line, and a normal for loop when it does not.
2. Write a function with a default value
A function is a named block. def starts it, and return hands a value back. Create func.py. The text in triple quotes right under the def line is the docstring: it says what the function does, and help(is_noisy) prints it. A caller can pass a value by position or by name.
func.py
def is_noisy(count, threshold=5):
"""Return True when count reaches the threshold."""
return count >= threshold
print(is_noisy(3))
print(is_noisy(3, threshold=2))
print(is_noisy(count=9))python3 func.pyFalse
True
True3. Build the classifier
Now put the pieces together. Create classify.py. The list LINES holds four lines of an authentication log; the next lesson reads them from a file. not in is the opposite of in. f"{kind:<9}" pads the text to nine characters. The last two lines mean "run main() only when this file is started as a program". Without them, importing the file from another file would run the whole program.
classify.py
LINES = [
"Nov 21 08:31:02 krbox sshd[811]: Failed password for root from 203.0.113.7 port 52144 ssh2",
"Nov 21 08:31:09 krbox sshd[812]: Failed password for invalid user admin from 203.0.113.7 port 52150 ssh2",
"Nov 21 08:32:41 krbox sshd[815]: Accepted publickey for alice from 192.0.2.50 port 40022 ssh2",
"Nov 21 08:33:00 krbox CRON[820]: pam_unix(cron:session): session opened for user root",
]
def classify(line):
"""Return 'failed', 'accepted' or 'other' for one auth log line."""
if "Failed password" in line:
return "failed"
if "Accepted" in line:
return "accepted"
return "other"
def source_address(line):
"""Return the address after ' from ', or None when the line has none."""
if " from " not in line:
return None
return line.split(" from ")[1].split()[0]
def main():
counts = {"failed": 0, "accepted": 0, "other": 0}
for line in LINES:
kind = classify(line)
counts[kind] += 1
print(f"{kind:<9} {source_address(line)}")
print(counts)
if __name__ == "__main__":
main()Two functions do one small job each: classify decides, and source_address extracts. main joins them. The if lines of classify are tried in order, and the first test that is true ends the function:
- Line arrives → Failed password?: look for the text in the line
- Failed password? → Return failed: yes: stop here
- Failed password? → Accepted?: no: try the next test
- Accepted? → Return accepted: yes: stop here
- Accepted? → Return other: no: nothing matched
4. Run it
python3 classify.pyfailed 203.0.113.7
failed 203.0.113.7
accepted 192.0.2.50
other None
{'failed': 2, 'accepted': 1, 'other': 1}The CRON line has no from, so source_address returned None. That is the correct answer, and the caller must expect it.
5. Use your function from another file
Python can import your file as a module. import classify makes its names available as classify.name. The form from classify import source_address brings one name in, so you write it without the prefix. The guard keeps main() from running.
python3 -c "import classify; print(classify.classify('Accepted publickey for bob'))"
python3 -c "from classify import source_address; print(source_address('Accepted for bob from 192.0.2.9 port 1'))"accepted
192.0.2.9Your turn
Do the task of the network team. There is no code here: use what the worked example showed.
First save gen3.py in ~/krlab/python. It makes the same forty invented firewall lines on every machine, because the seed of the random generator is fixed: random.Random(3) starts a generator at the value 3, and it then gives the same numbers every time. A line looks like this: Nov 21 09:01:07 krbox kernel: DENY tcp 203.0.113.9:55375 -> 10.0.0.5:22. The part after -> is the destination: the address and the port. In the generator, rng.choice(list) picks one item, rng.randint(a, b) picks a whole number from a to b, and :02d pads a number to two digits. You do not need to study the rest of it: it only makes the data.
gen3.py
import random
def make_lines():
"""Return 40 invented firewall lines. The seed is fixed, so everyone gets the same data."""
rng = random.Random(3)
sources = ["203.0.113.9", "198.51.100.14", "192.0.2.77", "10.0.0.8"]
ports = [22, 23, 80, 443, 445, 3306, 3389, 8080]
lines = []
for number in range(40):
action = rng.choice(["ALLOW", "DENY", "DENY"])
source = rng.choice(sources)
port = rng.choice(ports)
lines.append(
f"Nov 21 09:{number:02d}:07 krbox kernel: {action} tcp "
f"{source}:{rng.randint(40000, 60000)} -> 10.0.0.5:{port}"
)
return linesThen write fwcount.py. It starts with from gen3 import make_lines, and make_lines() gives you the list of lines. In it:
- Write a function
port_of(line)that returns the destination port as a number. - Write a function
risk(port, limit=1024). It returns"high"for the ports 23, 445, 3389 and 5900,"medium"for any other port belowlimit, and"low"for the rest. - Loop over the lines. For each line with
DENY, count it under its risk. Also count the denied lines for each source address. - Print the counts, and run the file only as a program (use the guard).
Check yourself
What is wrong with "if port = 22:"?
A single = stores a value. Python raises a SyntaxError here, because a test needs ==. The two signs do different jobs.
Why does a function that only prints a result give None when you store its value?
print shows a value on the screen, but it does not give it back. A function without return gives back None. When another part of your program needs the result, use return.
You change "return 'failed'" to "print('failed')" in classify. What happens to the counts?
print shows failed on the screen but does not stop the function. It carries on to the next if and ends at return "other". The counts become {'failed': 0, 'accepted': 1, 'other': 3}: every failed line is now counted as other. Only return hands a value to the caller and ends the function.
Why is the line "if __name__ == '__main__':" at the end of a script?
When Python starts a file as a program, __name__ is "__main__". When another file imports it, __name__ is the module name. The test lets one file be both a tool and a library.
Field notes
- Do not build a default value that can change:
def add(item, seen=[])keeps one list for every call, so results leak from call to call. Useseen=Noneand make the list inside the function. - A function that returns
Nonefor "not found" forces every caller to check. That is a common source ofAttributeError: 'NoneType'in parsers. Decide on purpose: returnNone, raise an error, or return an empty list. - Add type hints for the data that crosses a boundary:
def classify(line: str) -> str:. Python does not enforce them, but an editor and the toolmypyuse them to find mistakes before a run. - A substring test can be fooled, because a user name is part of the line.
"Accepted" in lineis also true for the lineInvalid user Accepted from 192.0.2.9, which is not a login. Anchor on the start of the message, for example"]: Accepted ", or use a regex (lesson 10). - Keep detection logic in small pure functions: the same input always gives the same output, and nothing is printed or read inside. You can then test a rule with one line of data, and reuse it in a batch job or a live alert.