-
Notifications
You must be signed in to change notification settings - Fork 0
/
checksum_maker.py
executable file
·70 lines (56 loc) · 1.8 KB
/
checksum_maker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env /usr/local/bin/python3
'''
** MODULE FOR ALL SCRIPTS, RECEIVES FILE PATH RETURNS CHECKSUM **
Actions of the script:
1. Checks the path input is legitimate, then stores sys.argv[1] as variable 'filepath'.
2. Passes the filepath to the md5_65536() function.
md5(file) chunk size 65536 (found to be fastest):
i. Opens the input file in read only bytes.
ii. Splits the file into chunks, iterates through 4096 bytes at a time.
iii. Returns the MD5 checksum, formatted hexdigest / Returns None if exception raised
4. The MD5 checksum is passed back to the calling script
Joanna White 2023
Python 3
'''
import os
import sys
import hashlib
import tenacity
def md5_65536(file):
'''
Hashlib md5 generation, return as 32 character hexdigest
'''
try:
hash_md5 = hashlib.md5()
with open(file, "rb") as fname:
for chunk in iter(lambda: fname.read(65536), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
except Exception:
return None
@tenacity.retry(stop=tenacity.stop_after_attempt(5))
def make_output_md5(filepath):
'''
Runs checksum generation/output to file as separate function allowing for easier retries
'''
try:
md5_checksum = md5_65536(filepath)
return md5_checksum
except Exception as err:
print(err)
return None
def make_checksum(filepath):
'''
Argument passed from calling script
Decorator for function ensures retries if Exceptions raised
'''
if not filepath:
print("No argument passed")
return None
if not os.path.isfile(filepath):
print("Supplied file path is not a file.")
return None
checksum = make_output_md5(filepath)
return checksum
if __name__ == "__main__":
make_checksum(sys.argv[1])