EZ LearnEZ Learn
Courses
EZ Board
Dashboard
All articles
python-for-cyber-securitypythondigital-forensicslogging

Setting Up a Python Forensic Environment

Work from a copy, never the original. Log every action, because an undocumented one proves nothing in court. A ten-line logging helper becomes the first brick of this unit's chain of custody.

Ashish Revar17 October 20265 min read
1 video lesson 6:09 total
Sign in to track your progress

Video lesson

Before the first line of forensic Python runs, a workstation needs a handful of things an ordinary development machine does not. None of them are complicated, but skipping any one of them weakens everything built on top.

Three things a forensic workstation needs

Work from a copy

Evidence is always worked from a copy, never the original, enforced with a hardware write-blocker when imaging physical media or simply by copying a file before touching it.

Log everything

Every script logs what it did and when, because an undocumented action is of little use as evidence.

A small, predictable toolkit

A short list of packages covers most of what this unit needs, so every machine in a team can be set up the same way.

The packages this unit uses

Most of the work in this unit comes from Python's own standard library, which needs no installation at all.

Tool in focus: hashlib and the standard library

hashlib (hashing), sqlite3 (reading browser and app databases), os (walking the file system) and datetime (timestamps) are all part of Python's standard library. They do most of the forensic work in this unit; the pip line below adds only file-type detection, image reading and PDF reading.

terminal

$ pip install python-magic pillow pypdf

Caution: python-magic on Windows

python-magic wraps a system library called libmagic, which Linux and macOS have installed already. On Windows, install python-magic-bin instead of python-magic; it bundles the library the wrapper needs. Everything else in this unit's code is identical either way.

PackageWhat it is for
hashlibComputing a file's hash (standard library)
sqlite3Reading browser and application databases (standard library)
os, datetimeWalking the file system, reading and converting timestamps (standard library)
python-magicIdentifying a file's true type from its content
pillowReading image files and their EXIF metadata
pypdfReading PDF files and their metadata

A logging helper every script in this unit shares

A minimal logging helper, used by every script from here on, keeps a timestamped record, which is the first brick of the chain of custody from the last article.

forensic_log.py

# forensic_log.py: a tiny, reusable logging helper
import datetime

def log_action(logfile, message):
    timestamp = datetime.datetime.now().isoformat()
    with open(logfile, "a") as f:
        f.write(f"{timestamp}  {message}\n")
    print(f"[{timestamp}] {message}")

Ten lines, and every script in this unit that touches a file calls it at least once. log_action does two things at once: it writes a permanent, timestamped line to a log file opened in append mode, the mode from Unit 1 that never erases what came before, and it prints the same line to the screen so the investigator sees progress in real time. Nothing about this function is forensic magic; it is the same with open(..., "a") pattern from Unit 1's file-handling article, pointed at a specific job.

Python concept: Why append mode, specifically

A forensic log must never lose an earlier entry, including one written moments before a crash. Mode "a" guarantees that: each call opens the file, writes one line, and closes it again, so even a script that dies partway through leaves every entry it managed to write intact. Mode "w", which overwrites on each run, would be exactly wrong here.

Try it yourself: Watch the log grow

Save forensic_log.py, then from the same folder run:

from forensic_log import log_action
log_action("test.log", "started examining evidence_copy/")
log_action("test.log", "hashed report.pdf")

Open test.log afterwards. Two lines, each with its own timestamp, in the order they happened. That file is the pattern every script in this unit builds on.

Check your understanding

Question 1: Name the three things a forensic workstation needs beyond an ordinary development machine.

Working only from copies of evidence, never the originals; logging every action a script takes, with a timestamp; and a small, predictable set of packages so every examiner's setup matches.

Question 2: Which of this unit's packages are part of Python's standard library, and which need pip?

hashlib, sqlite3, os and datetime are standard library and need no installation. python-magic, pillow and pypdf are third-party and are installed with pip (python-magic-bin on Windows).

Question 3: Why does log_action open its file in append mode rather than write mode?

Append mode guarantees that every call adds a line without erasing what came before, so even a script that fails partway through leaves a complete record up to that point. Write mode would erase the log's history on every run, which is the opposite of what a chain-of-custody record needs.

Key takeaway: Key takeaway

A forensic workstation differs from an ordinary one in three small but non-negotiable ways: copies, not originals; logged, not silent; a short, predictable toolkit. The ten-line logger built here is the thread that ties every script in this unit back to the chain of custody.

Assessments

Unit Assessment

Digital Forensics with Python

20 questions30 minPass: 60%

Start exam →

Comprehensive Assessment

Python for Cyber Security: Complete Assessment

100 questions120 minPass: 60%

Start final exam →

Related to this topic

Continue learning

Reference material

Cheatsheet

Python for Cyber Security — Cheatsheet

v1.0

Open resource

MCQ Bank

Python for Cyber Security — MCQ Bank

v1.0

Open resource

Question Bank

Python for Cyber Security — Question Bank

v1.0

Open resource

eBook

Python for Cyber Security — eBook

v1.0

Open resource

Discussion

Loading comments…
More articlesTest your knowledge
EZ MentorAI · Free

Setting Up a Python Forensic Environment

Hi! I'm EZ Mentor

Your AI tutor for
Setting Up a Python Forensic Environment

Sign in to ask, it's free.

EZ Mentor is AI-powered · Answers may not be perfect · 10 free questions / day

EZ Learn

Structured learning across Reverse Engineering, Cloud Security and Research Methodology, plus games and practice tools. Free, and open to anyone.

Learn

  • Courses
  • EZ Articles
  • EZ Watch
  • EZ Bytes
  • EZ Talks
  • Community

Library & Exams

  • All Resources
  • eBooks & PDFs
  • Question Banks
  • Cheatsheets
  • All Exams
  • EZ Board

EZ Arena

  • EZ Games
  • Byte Rush
  • Firewall Defence
  • 3D Case Files
  • Live Quiz
  • ML Challenges

EZ Cyber Hygiene

  • Hygiene Journey
  • Cyber Safety Check
  • दिशा - Hygiene
  • सजग - Awareness
  • अभ्यास - Practice
  • Scammed? Call 1930

Platform

  • About
  • Contact
  • Events
  • Verify Certificate
  • Terms of Use
  • Disclaimer

© 2026 EZ Learn by EpochZero. Educational content for learning purposes.

Platform Lead: Ashish Revar