Build a Python File Integrity Monitor: Catch Tampered Files the Moment They Change


Attackers who break into a server rarely leave a calling card — but they almost always leave changed files. A replaced binary, an edited config, a new startup script. The problem: nobody notices, because nobody memorized what those files looked like yesterday. A file integrity monitor solves this with one idea — hash everything important, save the hashes, and re-check them on a schedule. Let’s build one in Python.

The Code

import hashlib, json, os, sys
from pathlib import Path
BASELINE = Path("baseline.json")
def sha256(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
def scan(targets):
results = {}
for target in targets:
p = Path(target)
files = [p] if p.is_file() else p.rglob("*")
for f in files:
if f.is_file():
try:
results[str(f)] = sha256(f)
except (PermissionError, OSError):
pass
return results
def build_baseline(targets):
BASELINE.write_text(json.dumps(scan(targets), indent=2))
print(f"Baseline saved: {len(json.loads(BASELINE.read_text()))} files")
def check(targets):
old = json.loads(BASELINE.read_text())
new = scan(targets)
added = set(new) - set(old)
deleted = set(old) - set(new)
changed = {f for f in new if f in old and new[f] != old[f]}
if not (added or deleted or changed):
print("OK — no changes detected.")
return
print("ALERT — integrity changes detected:")
for f in sorted(added):
print(f" [+] ADDED: {f}")
for f in sorted(deleted):
print(f" [-] REMOVED: {f}")
for f in sorted(changed):
print(f" [!] CHANGED: {f}")
if __name__ == "__main__":
targets = sys.argv[2:]
if sys.argv[1] == "init":
build_baseline(targets)
elif sys.argv[1] == "check":
check(targets)
else:
print("Usage: python3 fim.py init <paths...> | check <paths...>")

How It Works

  1. init mode walks your chosen directories, computes a SHA-256 hash for every file, and saves the list as baseline.json. A hash is a fingerprint — change one byte of a file and its hash changes completely.
  2. check mode re-hashes everything and compares. Files that appear, disappear or change hash get printed as alerts.

Try It on Your Own Machine

mkdir -p ~/fim-test && echo "hello" > ~/fim-test/config.txt
python3 fim.py init ~/fim-test
echo "tampered" >> ~/fim-test/config.txt
python3 fim.py check ~/fim-test

You’ll see the [!] CHANGED alert immediately. That’s the whole tool working.

Automate It With Cron

A monitor you run by hand is a monitor you forget. Schedule it daily:

crontab -e
0 6 * * * python3 /home/anony/fim.py check /etc /home/anony/scripts >> /home/anony/fim.log 2>&1

Every morning at 6 AM you get a fresh integrity report in fim.log.

Choosing What to Watch

Monitor the files that matter and change rarely: /etc config files, your web server’s code, startup scripts, SSH keys and cron files. Don’t monitor log files or caches — they change constantly and will drown you in false alarms. And store the baseline somewhere safe: if an attacker can edit baseline.json, they can hide their changes. A copy on a USB stick or a read-only location is worth the effort.

Level Up

  • Email or message yourself on alerts instead of just logging them.
  • Hash file permissions and ownership too, not just content.
  • Compare against package manager data (debsums on Debian/Ubuntu) to verify system files against the official packages.

This is the same idea behind professional tools like Tripwire and AIDE — except you just built it in 60 lines. Defense doesn’t have to be expensive. Sometimes it’s a hash and a schedule.

Comments

Popular Posts