Lesson 02 · 40 minutes
Count failed logins with strings, lists and dictionaries
- Cut a log line into fields with string methods
- Store many values in lists, dictionaries and sets
- Count failed logins for each address with a dictionary
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
Overnight, your SSH server logged a burst of failed logins. The analyst on duty pastes twelve of the lines into the ticket and asks: "Who is hitting us, and is any of them one of ours?" You cannot answer by eye. You must cut each line into fields, count the failures for each address and compare the addresses with the list of staff addresses. The lesson uses the documentation addresses (203.0.113.0/24, 198.51.100.0/24, 192.0.2.0/24), which are safe to use in examples.
Recall
Lesson 1: which two values tell you that your script runs inside a virtual environment?
sys.prefix and sys.base_prefix. Inside a venv, sys.prefix is the venv folder and sys.base_prefix is the system Python that it came from, so the two differ.
Lesson 1: you run "python3 hello.py one". What is sys.argv[0], and what is sys.argv[1]?
sys.argv[0] is hello.py, the script name. sys.argv[1] is one, the first word that you typed after it. The same counting from zero applies to every list in this lesson.
The idea
Every value in Python has a type. These are the ones that you need now.
| Type | Example | Use it for |
|---|---|---|
str | "root" | Text: names, addresses, log lines. |
int, float | 22, 0.5 | Counts, ports, rates. |
bool | True, False | The result of a question. |
None | None | "No value". |
list | ["a", "b"] | An ordered group that you can change. |
dict | {"uid": 1001} | Pairs of key and value. Look up by key. |
set | {"a", "b"} | A group with no order and no duplicates. |
A list is for order, a dictionary is for lookup by name, and a set is for the question "is it in the group?". Counting starts at zero: the first item of a list is item[0], and item[-1] is the last.
Python marks a block of code with indentation: four spaces. A line that ends with a colon opens a block, and the indented lines under it belong to it. for x in group: runs its block once for each item of the group. Lesson 3 teaches the other block tools.
- Next line → Cut out address: split(" from ")[1].split()[0]
- Cut out address → Look up count: failed.get(address, 0)
- Look up count → Store count plus one: failed[address] = old count + 1
- Store count plus one → Next line: until the lines end
Worked example
1. Cut a log line into fields
Work in ~/krlab/python. Create strings.py. The line is a real sshd message, with extra spaces at both ends. The methods are:
strip()removes spaces at both ends of a text.split()with no argument cuts a text at every run of spaces and returns a list of words. With an argument,split(" from ")cuts at that exact text.startswith("x")asks whether a text begins withx.- The word
inasks whether a piece of text is inside another text.
split() gives each word a position, and the first word is position 0. This is the line of the script, cut at every space:
strings.py
line = " Nov 21 08:31:02 krbox sshd[811]: Failed password for root from 203.0.113.7 port 52144 ssh2 "
clean = line.strip()
parts = clean.split()
user = parts[8]
address = parts[10]
print(f"user={user} address={address}")
print("Failed" in clean)
print(address.startswith("203.0.113."))
print(clean.split(" from ")[1].split()[0])
print(len(parts), parts[-1])python3 strings.pyuser=root address=203.0.113.7
True
True
203.0.113.7
14 ssh2Counting words by position (parts[10]) breaks when the format changes. The fourth line is stronger: it cuts at from, takes the second piece, and takes the first word of it, which is the address.
2. Use numbers, booleans and None
Create numbers.py. int("52144") turns text into a whole number. type(x) tells the type of a value. bool(x) says whether Python counts a value as true. / divides, // divides and drops the fraction, and % gives the remainder. In an f-string, :.2f prints a number with two decimals.
numbers.py
port = int("52144")
print(port + 1, port > 1024)
print(7 / 2, 7 // 2, 7 % 2)
failures = 18
minutes = 60
print(f"{failures / minutes:.2f} failures a minute")
is_root = "root" == "root"
print(is_root, type(is_root))
owner = None
print(owner is None)
print(bool(""), bool("x"), bool(0), bool([]))python3 numbers.py52145 True
3.5 3 1
0.30 failures a minute
True <class 'bool'>
True
False True False FalseText from a log is always str, so convert it before you compare numbers. == tests equality. is None tests for "no value". Empty things ("", 0, []) count as false.
3. Keep many addresses in a list
Create collections_demo.py. [...] makes a list. The method append adds one item to the end. attempts[1:3] is a slice: a new list with items 1 and 2, and not 3. The loop for address in attempts[:2]: takes the first two items, one at a time, and runs the indented line for each. Do not forget the colon and the four spaces.
attempts = ["203.0.113.7", "198.51.100.23", "203.0.113.7", "203.0.113.7", "192.0.2.50"]
attempts.append("198.51.100.23")
print(attempts[0], attempts[-1], len(attempts))
print(attempts[1:3])
for address in attempts[:2]:
print("seen", address)4. Count with a dictionary
Add this to the same file. A dictionary {} stores pairs: failed[key] = value stores one. failed.get(key, 0) returns the stored value, or 0 when the key is new. The for loop runs the indented line for each address.
failed = {}
for address in attempts:
failed[address] = failed.get(address, 0) + 1
print(failed)
print(failed["203.0.113.7"])
print(failed.get("10.0.0.1", 0))The counting line reads the stored count (or 0), adds one and stores it back. failed["10.0.0.1"] without .get would raise a KeyError.
5. Compare groups with a set
Add this to collections_demo.py. set(attempts) makes a set: the same items with every duplicate removed. & keeps what is in both sets, and - keeps what is only in the first. A set has no order, so sorted() gives a fixed order for the output.
unique = set(attempts)
allowed = {"192.0.2.50", "192.0.2.51"}
print(len(unique), sorted(unique))
print(sorted(unique & allowed))
print(sorted(unique - allowed))6. Nest a list inside a dictionary
Add this to collections_demo.py too. A value of a dictionary can be a list. user["groups"][1] takes the key first, then the position. The word in on a dictionary tests the keys.
user = {"name": "alice", "uid": 1001, "groups": ["dev", "sudo"]}
user["shell"] = "/bin/bash"
print(user["groups"][1])
print(user)
print("uid" in user)This is the shape of most JSON that you meet (lesson 4).
7. Run the file
python3 collections_demo.py203.0.113.7 198.51.100.23 6
['198.51.100.23', '203.0.113.7']
seen 203.0.113.7
seen 198.51.100.23
{'203.0.113.7': 3, '198.51.100.23': 2, '192.0.2.50': 1}
3
0
3 ['192.0.2.50', '198.51.100.23', '203.0.113.7']
['192.0.2.50']
['198.51.100.23', '203.0.113.7']
sudo
{'name': 'alice', 'uid': 1001, 'groups': ['dev', 'sudo'], 'shell': '/bin/bash'}
True8. Meet Counter
The standard library has a class named Counter that does step 4 in one line. from collections import Counter brings the name Counter in from the standard library (lesson 3 explains imports). most_common() returns the pairs of item and count, the biggest count first. most_common(1) keeps only the first pair.
python3 -c "from collections import Counter; print(Counter(['a','b','a','c','a','b']).most_common())"[('a', 3), ('b', 2), ('c', 1)]Write the loop yourself first, so that you know what Counter does for you.
9. The finished file
This is the whole file as it stands after the steps above. The lab files of the course hold it.
The finished file: collections_demo.py
collections_demo.py
attempts = ["203.0.113.7", "198.51.100.23", "203.0.113.7", "203.0.113.7", "192.0.2.50"]
attempts.append("198.51.100.23")
print(attempts[0], attempts[-1], len(attempts))
print(attempts[1:3])
for address in attempts[:2]:
print("seen", address)
failed = {}
for address in attempts:
failed[address] = failed.get(address, 0) + 1
print(failed)
print(failed["203.0.113.7"])
print(failed.get("10.0.0.1", 0))
unique = set(attempts)
allowed = {"192.0.2.50", "192.0.2.51"}
print(len(unique), sorted(unique))
print(sorted(unique & allowed))
print(sorted(unique - allowed))
user = {"name": "alice", "uid": 1001, "groups": ["dev", "sudo"]}
user["shell"] = "/bin/bash"
print(user["groups"][1])
print(user)
print("uid" in user)Your turn
Do the task of the analyst. There is no code here: use what the worked example showed.
Create triage.py in ~/krlab/python. Start the file with this list. It is the data: the twelve lines of the ticket.
LINES = [
"Nov 21 10:02:11 krbox sshd[901]: Failed password for oracle from 198.51.100.40 port 41022 ssh2",
"Nov 21 10:02:14 krbox sshd[902]: Failed password for invalid user pi from 198.51.100.40 port 41030 ssh2",
"Nov 21 10:03:02 krbox sshd[905]: Accepted publickey for carol from 192.0.2.51 port 50210 ssh2",
"Nov 21 10:03:40 krbox sshd[907]: Failed password for root from 203.0.113.99 port 33001 ssh2",
"Nov 21 10:03:44 krbox sshd[908]: Failed password for root from 203.0.113.99 port 33007 ssh2",
"Nov 21 10:03:49 krbox sshd[909]: Failed password for invalid user test from 203.0.113.99 port 33012 ssh2",
"Nov 21 10:04:10 krbox sshd[912]: Failed password for dave from 192.0.2.50 port 40111 ssh2",
"Nov 21 10:04:58 krbox sshd[915]: Accepted password for dave from 192.0.2.50 port 40119 ssh2",
"Nov 21 10:05:21 krbox sshd[918]: Failed password for invalid user admin from 198.51.100.40 port 41051 ssh2",
"Nov 21 10:05:30 krbox sshd[919]: Failed password for root from 203.0.113.99 port 33044 ssh2",
"Nov 21 10:06:03 krbox sshd[921]: Failed password for root from 198.51.100.7 port 45500 ssh2",
"Nov 21 10:06:44 krbox sshd[925]: Failed password for invalid user ftp from 203.0.113.99 port 33090 ssh2",
]Below the list, write code that:
- Goes through the lines and keeps only those with a failed login.
- Takes the source address of each one (watch the lines with
invalid user) and counts the failures for each address in a dictionary. - Makes a set of all addresses with a failed login. The staff addresses are
192.0.2.50and192.0.2.51. Find the addresses that are not staff.
Then answer from your own output.
Check yourself
What does "failed.get(address, 0) + 1" do when the address is new?
get returns the default, 0, so the result is 1. The line stores that 1 under the new key. Without the default, failed[address] would raise a KeyError.
Why is parts[10] a weak way to read the address from a log line?
It depends on the position. An invalid user line, Failed password for invalid user bob from ..., has two more words, so index 10 holds a different word. Anchor on a marker such as " from ", or use a pattern.
You want to know which addresses in a log are not on your allow-list. Which type do you use?
Two sets and the - operator: seen - allowed. A set test is fast and removes duplicates for you.
What does attempts[-1] return, and what does attempts[1:3] return?
attempts[-1] is the last item. attempts[1:3] is a new list with the items at positions 1 and 2. The end position is not included.
Field notes
- Text from outside is never trusted. Log lines, usernames and headers can hold anything: spaces, quotes, control characters. A user name such as
a bbreaks a position-based split without an error. Check the shape of each field before you use it. - Do not compare addresses as text.
sorted(["10.0.0.9", "10.0.0.10"])puts.10first. Theipaddressmodule understands them:ipaddress.ip_address("203.0.113.7") in ipaddress.ip_network("203.0.113.0/24")isTrue, and it raisesValueErrorfor203.0.113.700. Usekey=ipaddress.ip_addressto sort in numeric order. - A dictionary keeps the order of insertion (Python 3.7 and later). A set does not. Never write a report that depends on set order: sort it.
floatis binary:0.1 + 0.2is0.30000000000000004. For counts and money useint; for exact decimals usedecimal.Decimal.- A list and a dictionary can be changed by any function that receives them. When you pass a shared list into a function and the function changes it, the caller sees the change. Copy it with
list(x)ordict(x)when you need to keep the original.