74 lines
2.0 KiB
Python
74 lines
2.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Checksum verification tool - verifies SHA256 checksums of files.
|
|
|
|
Usage:
|
|
python3 checksum_verify.py <checksum_file>
|
|
|
|
Format of checksum_file:
|
|
<sha256_hash> <filename>
|
|
(same as sha256sum output format)
|
|
"""
|
|
|
|
import hashlib
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def compute_sha256(filepath: str) -> str:
|
|
"""Compute SHA256 hash of a file."""
|
|
sha256_hash = hashlib.sha256()
|
|
with open(filepath, "rb") as f:
|
|
for chunk in iter(lambda: f.read(8192), b""):
|
|
sha256_hash.update(chunk)
|
|
return sha256_hash.hexdigest()
|
|
|
|
|
|
def verify_checksums(checksum_file: str) -> bool:
|
|
"""Verify all checksums in the file. Returns True if all pass."""
|
|
all_passed = True
|
|
with open(checksum_file, "r") as f:
|
|
for line_num, line in enumerate(f, 1):
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
parts = line.split()
|
|
if len(parts) < 2:
|
|
print(f"Line {line_num}: Invalid format - skipping")
|
|
all_passed = False
|
|
continue
|
|
expected_hash = parts[0]
|
|
filepath = " ".join(parts[1:])
|
|
|
|
if not Path(filepath).exists():
|
|
print(f"FAIL: {filepath} - file not found")
|
|
all_passed = False
|
|
continue
|
|
|
|
actual_hash = compute_sha256(filepath)
|
|
if actual_hash == expected_hash:
|
|
print(f"OK: {filepath}")
|
|
else:
|
|
print(f"FAIL: {filepath}")
|
|
print(f" Expected: {expected_hash}")
|
|
print(f" Actual: {actual_hash}")
|
|
all_passed = False
|
|
|
|
return all_passed
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print(__doc__)
|
|
sys.exit(1)
|
|
|
|
checksum_file = sys.argv[1]
|
|
if verify_checksums(checksum_file):
|
|
print("\nAll checksums verified successfully!")
|
|
sys.exit(0)
|
|
else:
|
|
print("\nSome checksums failed!")
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |