| e8555c89 Andy McCall |
1 |
from hashlib import new as newhash |
| 2 |
from os import stat |
| 3 |
from os.path import isfile |
| 4 |
import sys |
| 5 |
|
| 6 |
def verifyFile(filePath, fileLength, checksums): |
| 7 |
actualLength = stat(filePath).st_size |
| 8 |
if actualLength != fileLength: |
| 9 |
raise OSError( |
| 10 |
'Expected length %d, actual length %d' % (fileLength, actualLength) |
| 11 |
) |
| 12 |
hashers = {} |
| 13 |
for algo in checksums.keys(): |
| 14 |
try: |
| 15 |
hashers[algo] = newhash(algo) |
| 16 |
except ValueError as ex: |
| 17 |
raise OSError('Failed to create "%s" hasher: %s' % (algo, ex)) |
| 18 |
bufSize = 16384 |
| 19 |
with open(filePath, 'rb') as inp: |
| 20 |
while True: |
| 21 |
buf = inp.read(bufSize) |
| 22 |
if not buf: |
| 23 |
break |
| 24 |
for hasher in hashers.values(): |
| 25 |
hasher.update(buf) |
| 26 |
for algo, hasher in sorted(hashers.items()): |
| 27 |
if checksums[algo] != hasher.hexdigest(): |
| 28 |
raise OSError('%s checksum mismatch' % algo) |
| 29 |
|
| 30 |
def main(filePath, fileLengthStr, checksumStrs): |
| 31 |
if not isfile(filePath): |
| 32 |
print('No such file: %s' % filePath, file=sys.stderr) |
| 33 |
sys.exit(2) |
| 34 |
try: |
| 35 |
fileLength = int(fileLengthStr) |
| 36 |
except ValueError: |
| 37 |
print('Length should be an integer', file=sys.stderr) |
| 38 |
sys.exit(2) |
| 39 |
checksums = {} |
| 40 |
for checksumStr in checksumStrs: |
| 41 |
try: |
| 42 |
algo, hashval = checksumStr.split('=') |
| 43 |
except ValueError: |
| 44 |
print('Invalid checksum format: %s' % checksumStr, file=sys.stderr) |
| 45 |
sys.exit(2) |
| 46 |
else: |
| 47 |
checksums[algo] = hashval |
| 48 |
print('Validating: %s' % filePath) |
| 49 |
try: |
| 50 |
verifyFile(filePath, fileLength, checksums) |
| 51 |
except OSError as ex: |
| 52 |
print('Validation FAILED: %s' % ex, file=sys.stderr) |
| 53 |
sys.exit(1) |
| 54 |
else: |
| 55 |
print('Validation passed') |
| 56 |
sys.exit(0) |
| 57 |
|
| 58 |
if __name__ == '__main__': |
| 59 |
if len(sys.argv) >= 3: |
| 60 |
main( |
| 61 |
sys.argv[1], |
| 62 |
sys.argv[2], |
| 63 |
sys.argv[3 : ] |
| 64 |
) |
| 65 |
else: |
| 66 |
print( |
| 67 |
'Usage: python3 checksum.py FILE LENGTH (ALGO=HASH)*', |
| 68 |
file=sys.stderr |
| 69 |
) |
| 70 |
sys.exit(2) |