Skip to content

File integrity Checker  #7

Description

@sujakrishnasamy

import hashlib
import os
import json

Function to calculate the hash of a file

def calculate_hash(file_path):
sha256_hash = hashlib.sha256()
try:
with open(file_path, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
except FileNotFoundError:
return None

Function to create or update the hash registry

def generate_hashes(directory, output_file="hashes.json"):
hash_data = {}
for root, dirs, files in os.walk(directory):
for file in files:
path = os.path.join(root, file)
hash_data[path] = calculate_hash(path)
with open(output_file, "w") as f:
json.dump(hash_data, f, indent=4)
print(f"Hashes stored in {output_file}")

Function to check file integrity

def check_integrity(directory, hash_file="hashes.json"):
if not os.path.exists(hash_file):
print("Hash file not found. Run generate_hashes() first.")
return

with open(hash_file, "r") as f:
    old_hashes = json.load(f)

for path, old_hash in old_hashes.items():
    new_hash = calculate_hash(path)
    if new_hash is None:
        print(f"[MISSING] {path}")
    elif new_hash != old_hash:
        print(f"[MODIFIED] {path}")
    else:
        print(f"[OK] {path}")

=== USAGE ===

Step 1: Generate hashes (run once initially)

generate_hashes("path_to_your_directory")

Step 2: Check file integrity later

check_integrity("path_to_your_directory")

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions