UnixDroid

Lesson 4 of 12 · 7 min

Files, functions and errors: read wordlists and logs

Real security scripts read their data - huge wordlists and server logs. Here are the three skills that turn a toy script into a real tool.

Real security scripts rarely work with data you typed by hand. They read it — a wordlist of a million passwords, a web server's log, a list of targets. This lesson covers the three skills that turn a toy script into a real tool: reading files, wrapping logic in functions, and surviving errors.

Reading a file line by line

Wordlists and logs can be huge, so read them one line at a time instead of loading the whole file into memory.

with open('wordlist.txt') as f:
    for line in f:
        word = line.strip()   # remove the newline
        print(word)

strip() is essential — without it, every word secretly ends in a newline and your comparisons silently fail.

Functions: write once, reuse everywhere

A function packages logic behind a name so you can call it again and again.

def is_interesting(line):
    return 'failed password' in line.lower()

with open('auth.log') as f:
    for line in f:
        if is_interesting(line):
            print(line.strip())

Now you have a reusable log filter — change one function and every caller updates.

Handling errors so one bad line doesn't crash everything

Networks time out, files go missing, hosts refuse connections. A tool that dies on the first problem is useless across 1,000 targets.

try:
    with open('targets.txt') as f:
        data = f.read()
except FileNotFoundError:
    print('No targets file — create targets.txt first')
PatternWhy it matters
with open(...)Closes the file automatically, even on error
.strip()Kills trailing newlines that break matches
try / exceptKeeps the run alive when one item fails
FunctionsStop copy-pasting the same five lines

Tip: Catch specific errors (FileNotFoundError, ConnectionRefusedError) rather than a bare except. A blanket catch hides the very bugs you need to see.

With file reading, functions and error handling, you can feed any tool real-world data.

Try it yourself
  1. Make a wordlist.txt with five words and print each one stripped.
  2. Write a function contains_admin(line) that returns True when 'admin' appears.
  3. Wrap your file-opening code in a try/except that prints a friendly message if the file is missing.
No Linux machine? Practise in the free online terminal

Quick check

Which string method removes the trailing newline from each line you read from a file?

Need a hint?

It trims whitespace off both ends.

Finished this lesson?

Done lessons keep your daily streak going 🔥

0 day streak

0 lessons done

best 0 days

Log in to keep your streak on every device →