43 lines
1.0 KiB
Python
43 lines
1.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Calculate SHA256 and MD5 hashes for files. Utility snippet."""
|
|
|
|
import hashlib
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def sha256_hash(filepath: str) -> str:
|
|
"""Return SHA256 hash of file contents."""
|
|
h = hashlib.sha256()
|
|
with open(filepath, 'rb') as f:
|
|
for chunk in iter(lambda: f.read(8192), b''):
|
|
h.update(chunk)
|
|
return h.hexdigest()
|
|
|
|
|
|
def md5_hash(filepath: str) -> str:
|
|
"""Return MD5 hash of file contents."""
|
|
h = hashlib.md5()
|
|
with open(filepath, 'rb') as f:
|
|
for chunk in iter(lambda: f.read(8192), b''):
|
|
h.update(chunk)
|
|
return h.hexdigest()
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: file_hashes.py <file1> [file2...]")
|
|
sys.exit(1)
|
|
|
|
for path in sys.argv[1:]:
|
|
p = Path(path)
|
|
if not p.exists():
|
|
print(f"File not found: {p}")
|
|
continue
|
|
print(f"{p}")
|
|
print(f" SHA256: {sha256_hash(path)}")
|
|
print(f" MD5: {md5_hash(path)}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |