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')
| Pattern | Why it matters |
|---|---|
with open(...) | Closes the file automatically, even on error |
.strip() | Kills trailing newlines that break matches |
try / except | Keeps the run alive when one item fails |
| Functions | Stop copy-pasting the same five lines |
Tip: Catch specific errors (
FileNotFoundError,ConnectionRefusedError) rather than a bareexcept. 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.