|
import os |
|
import hashlib |
|
import sys |
|
import argparse |
|
import collections |
|
|
|
def absoluteFilePaths(directory): |
|
for dirpath,_,filenames in os.walk(directory): |
|
for f in filenames: |
|
yield os.path.abspath(os.path.join(dirpath, f)) |
|
|
|
|
|
def generate_hash_md5(filepath): |
|
with open(filepath, "rb") as f: |
|
file_hash = hashlib.md5() |
|
while chunk := f.read(8192): |
|
file_hash.update(chunk) |
|
return file_hash.hexdigest() |
|
|
|
|
|
def generate_hash_sha1(filepath): |
|
with open(filepath, "rb") as f: |
|
file_hash = hashlib.sha1() |
|
while chunk := f.read(8192): |
|
file_hash.update(chunk) |
|
return file_hash.hexdigest() |
|
|
|
def write_to_file(hash_dict, output_txt): |
|
with open(output_txt, 'w') as f: |
|
for filename, hashvalue in hash_dict.items(): |
|
print(hash_dict) |
|
f.write("%s : %s\n" %(filename, hashvalue)) |
|
|
|
|
|
def main(): |
|
parser = argparse.ArgumentParser(description='Process some hashes for exe files') |
|
parser.add_argument('dir_path', type=str, help='directory path to get hash') |
|
args = parser.parse_args() |
|
directory_path = args.dir_path |
|
|
|
list_of_all_files = absoluteFilePaths(directory_path) |
|
|
|
md5hashdict = collections.defaultdict(str) |
|
sha1hashdict = collections.defaultdict(str) |
|
|
|
for exe_file in list_of_all_files: |
|
md5hashdict[os.path.basename(exe_file)] = generate_hash_md5(exe_file) |
|
sha1hashdict[os.path.basename(exe_file)] = generate_hash_sha1(exe_file) |
|
|
|
|
|
write_to_file(md5hashdict, 'md5.txt') |
|
write_to_file(sha1hashdict, 'sha1.txt') |
|
|
|
if __name__ == "__main__": |
|
main() |