Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 04 · 40 minutes

Read logs and write JSON and CSV reports

After this lesson you can
  • Read a log file one line at a time, without loading all of it
  • Write and read JSON and CSV files
  • Handle a file that is not valid UTF-8
Lab files of this lesson (14)

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

The network team sends you the log of the company DNS resolver for one hour, and the SOC asks: "Does any machine ask for names that do not exist? Send us the numbers in a file that our spreadsheet and our dashboard can both read." The log comes from a program that does not care about clean text, and some lines hold bytes that are not valid text. Your tool must survive them, and its report must be both JSON and CSV.

Recall

Lesson 2: what does failed.get(address, 0) + 1 give for an address that is not yet a key?

1. get returns the default 0 for a missing key, and the line adds one. You store the result back under the key, so the next line finds 1 and makes it 2.

Lesson 3: what does a function without a return statement give back?

None. If another part of the program needs the result, the function must return it. A print only shows the value on the screen.

The idea

A file holds bytes. Python turns the bytes into text with an encoding. Use UTF-8 and say so every time.

Three habits make file code safe:

  • Use with open(...) as handle:. The with block closes the file when it ends, even after an error.
  • Loop over the file object (for line in handle). Python then reads one line at a time. handle.read() loads the whole file at once.
  • Use pathlib.Path for paths. It treats a path as an object, so you do not glue text with / by hand.
FormatModuleBest for
JSONjsonNested data and the exchange with other programs.
CSVcsvFlat tables that a person opens in a spreadsheet.
From a log file to two reports
Log fileYour scriptreport.jsonreport.csvone line at a timecount in a dictionarydumps makes the text, write_text saves itDictWriter writes one row eachLog fileYour scriptreport.jsonreport.csv1234
  1. Log file → Your script: one line at a time
  2. Your script: count in a dictionary
  3. Your script → report.json: dumps makes the text, write_text saves it
  4. Your script → report.csv: DictWriter writes one row each

Worked example

1. Make a sample log

Work in ~/krlab/python. mkdir -p makes a folder, and cat > file <<'EOF' writes the lines up to EOF into a file. The quotes around EOF pass the text unchanged. The log has five lines.

mkdir -p ~/krlab/python/data
cd ~/krlab/python
cat > data/auth.log <<'EOF'
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
Nov 21 08:34:12 krbox sshd[830]: Failed password for bob from 198.51.100.23 port 33310 ssh2
EOF

2. Read it line by line

Create readlog.py. The new words:

  • Path("data/auth.log") makes a path object. It has the parts .name, .suffix (the ending, such as .log) and .parent, and the methods .exists() and .stat() (facts about the file, such as st_size, the size in bytes).
  • log.open(...) opens a file for reading (the default mode; the parts are in the drawing below). errors="replace" turns a byte that is not valid text into a mark instead of stopping (step 6 shows it).
  • enumerate(handle, start=1) gives a line number with each line.
  • rstrip("\n") removes the line end from the right.
  • line[:40] is a slice of the first 40 characters.
  • The mode "w" creates a file and erases old content, so check the name first. handle.write(text) writes text as it is, and print(..., file=handle) writes a line. The mode "a" adds to the end.
  • read_text loads a whole file: good for a small file, wrong for a log.
  • print(text, end="") prints with no line end added, because the text already ends with one. The normal print adds a line end.
The line that opens the log
withcloses the file at the endlog.open(open the file of the pathencoding="utf-8"how the bytes become texterrors="replace"bad byte becomes a mark) as handle:handle is the open filewithcloses the file at the endlog.open(open the file of the pathencoding="utf-8"how the bytes become texterrors="replace"bad byte becomes a mark) as handle:handle is the open file

readlog.py

from pathlib import Path

log = Path("data/auth.log")
print(log.exists(), log.name, log.suffix, log.parent)
print(log.stat().st_size, "bytes")

failed = 0
with log.open(encoding="utf-8", errors="replace") as handle:
    for number, line in enumerate(handle, start=1):
        line = line.rstrip("\n")
        if "Failed password" in line:
            failed += 1
            print(number, line[:40])
print("failed:", failed)

out = Path("data/failed.txt")
with out.open("w", encoding="utf-8") as handle:
    handle.write("failed logins: 3\n")
    print("second line", file=handle)
print(out.read_text(encoding="utf-8"), end="")
python3 readlog.py
True auth.log .log data
468 bytes
1 Nov 21 08:31:02 krbox sshd[811]: Failed 
2 Nov 21 08:31:09 krbox sshd[812]: Failed 
5 Nov 21 08:34:12 krbox sshd[830]: Failed 
failed: 3
failed logins: 3
second line

3. Write and read JSON

Create jsoncsv.py. The first half is JSON. json.dumps turns a dictionary into JSON text, and indent=2 makes it readable. write_text writes a text into a file in one call. json.load reads a file and gives back dictionaries, lists, strings and numbers. JSON has no set type, and None becomes null.

import csv
import json
from pathlib import Path

failed = {"203.0.113.7": 2, "198.51.100.23": 1}
report = {"source": "data/auth.log", "failed_by_address": failed, "total": 3}

Path("data/report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
with open("data/report.json", encoding="utf-8") as handle:
    loaded = json.load(handle)
print(loaded["failed_by_address"]["203.0.113.7"], type(loaded))

4. Write and read CSV

Add the second half to the same file. csv.DictWriter writes one dictionary for each row, and writeheader() writes the column names first. csv.DictReader gives each row back as a dictionary. failed.items() gives the pairs of key and value of a dictionary, and for address, count in ... takes one pair at a time and names its two parts. newline="" is required for the csv module, or you get blank lines on some systems. Every value from a CSV is text, so convert with int().

with open("data/failed.csv", "w", newline="", encoding="utf-8") as handle:
    writer = csv.DictWriter(handle, fieldnames=["address", "count"])
    writer.writeheader()
    for address, count in failed.items():
        writer.writerow({"address": address, "count": count})

with open("data/failed.csv", newline="", encoding="utf-8") as handle:
    for row in csv.DictReader(handle):
        print(row["address"], int(row["count"]))

5. Run it and look at the files

cat prints files.

python3 jsoncsv.py
cat data/report.json data/failed.csv
2 <class 'dict'>
203.0.113.7 2
198.51.100.23 1
{
  "source": "data/auth.log",
  "failed_by_address": {
    "203.0.113.7": 2,
    "198.51.100.23": 1
  },
  "total": 3
}
address,count
203.0.113.7,2
198.51.100.23,1

6. Break the encoding on purpose

Real logs hold bytes that are not UTF-8. printf with \xe9 writes the byte for "e with an acute accent" in Latin-1. Then read the file two ways. try runs a block, and except UnicodeDecodeError catches that one error (lesson 5 teaches this in full).

printf 'Failed password for caf\xe9 from 192.0.2.9\n' > data/latin.log
python3 -c "
try:
    open('data/latin.log', encoding='utf-8').read()
except UnicodeDecodeError as e:
    print(e)
print(open('data/latin.log', encoding='utf-8', errors='replace').read(), end='')"
'utf-8' codec can't decode byte 0xe9 in position 23: invalid continuation byte
Failed password for caf� from 192.0.2.9

With errors="replace" the bad byte becomes the mark �, and the program goes on. In Python this mark is the character "�". An attacker can put bytes like this in a user name on purpose, to crash a log parser.

7. 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: jsoncsv.py

jsoncsv.py

import csv
import json
from pathlib import Path

failed = {"203.0.113.7": 2, "198.51.100.23": 1}
report = {"source": "data/auth.log", "failed_by_address": failed, "total": 3}

Path("data/report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
with open("data/report.json", encoding="utf-8") as handle:
    loaded = json.load(handle)
print(loaded["failed_by_address"]["203.0.113.7"], type(loaded))

with open("data/failed.csv", "w", newline="", encoding="utf-8") as handle:
    writer = csv.DictWriter(handle, fieldnames=["address", "count"])
    writer.writeheader()
    for address, count in failed.items():
        writer.writerow({"address": address, "count": count})

with open("data/failed.csv", newline="", encoding="utf-8") as handle:
    for row in csv.DictReader(handle):
        print(row["address"], int(row["count"]))

Your turn

Do the task of the SOC. There is no code here: use what the worked example showed.

Save gen4.py in ~/krlab/python. It writes an invented DNS log with a fixed seed, so every reader gets the same file. A line looks like the drawing. The answer NXDOMAIN means "that name does not exist". The program writes the file in Latin-1, so a few lines hold a byte that is not valid UTF-8. You do not need to study this generator: it only makes the data.

One line of the DNS log
09:00:01the time10.0.0.23the client that asksAthe record type: an addressexample.orgthe name that it asks forNOERRORthe answer (NXDOMAIN: no name)09:00:01the time10.0.0.23the client that asksAthe record type: an addressexample.orgthe name that it asks forNOERRORthe answer (NXDOMAIN: no name)

gen4.py

import random
import sys

rng = random.Random(4)
CLIENTS = ["10.0.0.12", "10.0.0.15", "10.0.0.23", "10.0.0.40", "10.0.0.41"]
NAMES = ["example.org", "mail.example.org", "updates.example.net", "cdn.example.com", "intranet.example.org"]
LETTERS = "abcdefghijklmnopqrstuvwxyz0123456789"

with open(sys.argv[1], "w", encoding="latin-1") as out:
    for second in range(250):
        stamp = f"09:{second // 60:02d}:{second % 60:02d}"
        client = rng.choices(CLIENTS, [3, 2, 2, 6, 1])[0]
        roll = rng.random()
        if client == "10.0.0.40" and roll < 0.55:
            name = "".join(rng.choice(LETTERS) for _ in range(10)) + ".example.net"
            answer = "NXDOMAIN"
        elif roll < 0.04:
            name = "caf\xe9.example.org"
            answer = "NOERROR"
        elif roll < 0.09:
            name = "old-printer.example.org"
            answer = "NXDOMAIN"
        else:
            name = rng.choice(NAMES)
            answer = "NOERROR"
        out.write(f"{stamp} {client} A {name} {answer}\n")

Run python3 gen4.py dns.log. Then write dns_summary.py. It must:

  1. Read dns.log one line at a time, with UTF-8 and errors="replace".
  2. Count all lines, the lines with the answer NXDOMAIN, and the lines that contain the mark "�". You can type this mark in code as "\ufffd". Count the NXDOMAIN lines for each client, too.
  3. Write dns_summary.json with the keys lines, nxdomain, bad_bytes and nxdomain_by_client.
  4. Write dns_summary.csv with the columns client and nxdomain, one row for each client that has at least one.

Open both files to see that they are right. Then answer from your own results.

Check yourself

You must find one address in a 6 GB log. Why is open(...).read() the wrong choice?

read() loads the whole file into memory, so the program can be killed or can slow the machine. A for line in handle loop holds one line at a time, and memory use stays small.

What does the with statement give you that a plain open() does not?

It closes the file at the end of the block, also when an exception happens inside it. A file that stays open can lose buffered data and can hit the limit of open files in a long-running program.

You open a report with mode "w" and the file already holds a day of data. What happens?

The old content is erased at once, before you write anything. Use "a" to add, or write to a new name (for example with the date), and check the path first.

A column in a CSV holds the number 7. What does row["count"] give?

The text "7", not the number. The csv module does not guess types. Convert with int(row["count"]); as text, "7" > "10" is true, which gives a wrong answer.

Field notes

  • Do not load a pickle file from outside. pickle.load can run any code that the file's author chose. JSON only builds data. Use JSON for everything that crosses a trust boundary.
  • A relative path depends on the working directory. A scheduled job runs somewhere else. Use Path(__file__).resolve().parent / "data", or take the path as an argument (lesson 5).
  • Check where a path ends up when a user supplies a part of it. This weakness is called path traversal (a class of weakness in the CWE list, and part of the OWASP Top 10 category Broken Access Control). Path("reports") / name with name = "../../etc/cron.d/x" leaves the folder. Resolve the result and test it with .is_relative_to(base) (Python 3.9 and later) before you write.
  • A spreadsheet runs a cell that starts with =, +, - or @ as a formula. If a report holds text from an attacker (a user name), prefix such a cell with a single quote before you give the CSV to a person who opens it in Excel.
  • For a rotated log such as auth.log.2.gz, use gzip.open(path, "rt", encoding="utf-8"): the rest of your code does not change. For a huge file with one JSON record on each line (JSON Lines), call json.loads(line) for each line.