|
| 1 | +# Import the libraries we need for this script |
| 2 | +import hashlib |
| 3 | +import optparse |
| 4 | +import os |
| 5 | +import os.path |
| 6 | +import sys |
| 7 | +from gooey import Gooey, GooeyParser |
| 8 | + |
| 9 | +def read_hash_from_md5_file(md5_filename): |
| 10 | + """This function reads a hash out of a .md5 file.""" |
| 11 | + |
| 12 | + with open(md5_filename) as file: |
| 13 | + for line in file: |
| 14 | + possible_hash = pos = line.split(",")[1] |
| 15 | + if len(possible_hash) == 32: |
| 16 | + return possible_hash |
| 17 | + |
| 18 | + return None # failed to find the hash |
| 19 | + |
| 20 | + |
| 21 | +def generate_md5_hash(filename, block_size=2 ** 20, progress_blocks=128): |
| 22 | + """This function generates an md5 hash for a given file.""" |
| 23 | + |
| 24 | + md5 = hashlib.md5() |
| 25 | + blocks = 0 |
| 26 | + total_blocks = 1 + (os.path.getsize(filename) / block_size) |
| 27 | + with open(filename, 'rb') as file: |
| 28 | + while True: |
| 29 | + data = file.read(block_size) |
| 30 | + if not data: |
| 31 | + break |
| 32 | + md5.update(data) |
| 33 | + # Display progress in the command line |
| 34 | + if (blocks % progress_blocks) == 0: |
| 35 | + percentage_string = "{0}%".format(100 * blocks / total_blocks) |
| 36 | + sys.stdout.write("\r{1:<10}{0}".format(filename, percentage_string)) |
| 37 | + sys.stdout.flush() |
| 38 | + blocks += 1 |
| 39 | + return md5.hexdigest() |
| 40 | + |
| 41 | + |
| 42 | +def check_against_md5_file(filename, md5_filename): |
| 43 | + """This function checks a filename against its md5 filename.""" |
| 44 | + |
| 45 | + # Get the expected hash from the .md5 file |
| 46 | + expected_hash = read_hash_from_md5_file(md5_filename) |
| 47 | + |
| 48 | + # If we couldn't read the expected hash, return an error |
| 49 | + if expected_hash is None: |
| 50 | + print("ERROR {0}".format(filename)) |
| 51 | + print("Could not read a valid md5 hash from {0}".format(md5_filename)) |
| 52 | + return (filename, 'could not read from .md5 file', 'not generated') |
| 53 | + |
| 54 | + # Generate the actual hash for the file being protected |
| 55 | + actual_hash = generate_md5_hash(filename) |
| 56 | + |
| 57 | + # Print out success or failure messages |
| 58 | + error = None |
| 59 | + if actual_hash == expected_hash: |
| 60 | + sys.stdout.write("\rOK {0}\n".format(filename)) |
| 61 | + sys.stdout.flush() |
| 62 | + else: |
| 63 | + sys.stdout.write("\rERROR {0}\n".format(filename)) |
| 64 | + sys.stdout.flush() |
| 65 | + print(" expected hash {0}".format(expected_hash)) |
| 66 | + print(" actual hash is {0}".format(actual_hash)) |
| 67 | + error = (filename, expected_hash, actual_hash) |
| 68 | + |
| 69 | + return error |
| 70 | + |
| 71 | + |
| 72 | +def generate_md5_file_for(filename, md5_filename): |
| 73 | + """This function generates an md5 file for an existing file.""" |
| 74 | + try: |
| 75 | + output_file = open(md5_filename, 'w') |
| 76 | + except IOError: |
| 77 | + sys.stdout.write("ERROR: can't write to file {0}\n".format(md5_filename)) |
| 78 | + |
| 79 | + generated_hash = generate_md5_hash(filename) |
| 80 | + file_size = os.path.getsize(filename) |
| 81 | + output_file.write("{0},{1},{2}\n".format(os.path.basename(filename),generated_hash,file_size)) |
| 82 | + output_file.close() |
| 83 | + |
| 84 | + sys.stdout.write("\rDONE {0}\n".format(filename)) |
| 85 | + sys.stdout.flush() |
| 86 | + |
| 87 | + |
| 88 | +def get_file_info_dictionaries(dirs): |
| 89 | + """Walk the directories recursively and match up .mnf files to the files they describe.""" |
| 90 | + |
| 91 | + # Recursively walk the directories, trying to pair up the .md5 files |
| 92 | + file_info_dicts = {} |
| 93 | + for (dirpath, dirnames, filenames) in os.walk(dirs): |
| 94 | + for each_filename in filenames: |
| 95 | + full_file_path = os.path.join(dirpath, each_filename) |
| 96 | + is_md5_file = (full_file_path[-4:].lower() == '.mnf') |
| 97 | + if is_md5_file: |
| 98 | + key = full_file_path[:-4] |
| 99 | + else: |
| 100 | + key = full_file_path |
| 101 | + d = file_info_dicts.setdefault(key, dict(file=False, md5=False)) |
| 102 | + if is_md5_file: |
| 103 | + d['md5'] = True |
| 104 | + else: |
| 105 | + d['file'] = True |
| 106 | + |
| 107 | + # Print information about what was found |
| 108 | + files_found = 0 |
| 109 | + md5_found = 0 |
| 110 | + both_found = 0 |
| 111 | + for file_name, d in iter(file_info_dicts.items()): |
| 112 | + if d['md5'] and d['file']: |
| 113 | + both_found += 1 |
| 114 | + elif d['file']: |
| 115 | + files_found += 1 |
| 116 | + elif d['md5']: |
| 117 | + md5_found += 1 |
| 118 | + |
| 119 | + print("Found {0} files with matching .mnf files.".format(both_found)) |
| 120 | + print("Found {0} .mnf files with no matching file.".format(md5_found)) |
| 121 | + print("Found {0} files with no matching .mnf file.".format(files_found)) |
| 122 | + |
| 123 | + return file_info_dicts |
| 124 | + |
| 125 | +@Gooey( |
| 126 | + program_name='Mnftool', |
| 127 | + menu=[{ |
| 128 | + 'name': 'File', |
| 129 | + 'items': [{ |
| 130 | + 'type': 'AboutDialog', |
| 131 | + 'menuTitle': 'About', |
| 132 | + 'name': 'Mnftool', |
| 133 | + 'description': 'Python based', |
| 134 | + 'version': '2.1', |
| 135 | + 'copyright': '2022', |
| 136 | + 'website': '', |
| 137 | + 'developer': 'Michael Akridge'}] |
| 138 | + |
| 139 | + }] |
| 140 | +) |
| 141 | + |
| 142 | + |
| 143 | +def parse_args(): |
| 144 | + parser = GooeyParser(description='MNF Tool Checker & Generator.') |
| 145 | + parser.add_argument('SELECT_FILE_FOLDER', widget="DirChooser") |
| 146 | + parser.add_argument('SELECT_OPERATION',choices=['check','generate']) |
| 147 | + return parser.parse_args() |
| 148 | + |
| 149 | +def main(): |
| 150 | + args = parse_args() |
| 151 | + dirs = args.SELECT_FILE_FOLDER |
| 152 | + operation = args.SELECT_OPERATION |
| 153 | + file_info_dicts = get_file_info_dictionaries(dirs) |
| 154 | + if operation == 'check': |
| 155 | + # Check each pair of matching files |
| 156 | + num_checked = 0 |
| 157 | + errors = [] |
| 158 | + for filename, d in sorted(iter(file_info_dicts.items())): |
| 159 | + if d['file'] and d['md5']: |
| 160 | + error = check_against_md5_file(filename, filename + '.mnf') |
| 161 | + if error: |
| 162 | + errors.append(error) |
| 163 | + num_checked += 1 |
| 164 | + print("===============================================================") |
| 165 | + print("SUMMARY") |
| 166 | + print("{0} files checked.".format(num_checked)) |
| 167 | + print("{0} had errors.".format(len(errors))) |
| 168 | + for (filename, expected_hash, actual_hash) in errors: |
| 169 | + print(filename) |
| 170 | + print(" expected hash {0}".format(expected_hash)) |
| 171 | + print(" actual hash is {0}".format(actual_hash)) |
| 172 | + print("===============================================================") |
| 173 | + |
| 174 | + elif operation == 'generate': |
| 175 | + print(file_info_dicts) |
| 176 | + # Generate an .md5 file for files which don't have one |
| 177 | + for filename, d in sorted(iter(file_info_dicts.items())): |
| 178 | + if d['file'] and not d['md5']: |
| 179 | + generate_md5_file_for(filename, filename + '.mnf') |
| 180 | + print("===============================================================") |
| 181 | + |
| 182 | + |
| 183 | +if __name__ == "__main__": |
| 184 | + main() |
0 commit comments