Skip to content

Instantly share code, notes, and snippets.

@light-bringer
Last active July 15, 2020 17:25
Show Gist options
  • Select an option

  • Save light-bringer/53a3c153707c4f798e5898471898ba3d to your computer and use it in GitHub Desktop.

Select an option

Save light-bringer/53a3c153707c4f798e5898471898ba3d to your computer and use it in GitHub Desktop.
Hash generation Utility scripts
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()
C:\Users\debapriya.das\Desktop\desktop.ini : 9e36cc3537ee9ee1e3b10fa4e761045b
C:\Users\debapriya.das\Desktop\hashcode_muncher.py : 1b74979c0d408b4ffb56287d5ec5ad56
C:\Users\debapriya.das\Desktop\JioMeet.appref-ms : a27f53b8ec6facfb014b8be517d11fea
C:\Users\debapriya.das\Desktop\md5.txt : fbbf1c4ebf2525894489b8daf41c65c3
C:\Users\debapriya.das\Desktop\Microsoft Edge.lnk : 377e6a445993c4d519284d81fcb4bec2
C:\Users\debapriya.das\Desktop\sha1.txt : d41d8cd98f00b204e9800998ecf8427e
C:\Users\debapriya.das\Desktop\Software Center.lnk : 8d23f05efc3bc73acbab873c8c2e650d

This is a utility script that generates md5 hash and sha1 hash of all files present in a directory/subdirectory and outputs the same in txt files.

  • sha1.txt
  • md5.txt

Run the following command to execute the utility script.

PS C:\Users\debapriya.das\Desktop> python .\hashcode_muncher.py
usage: hashcode_muncher.py [-h] dir_path
hashcode_muncher.py: error: the following arguments are required: dir_path

PS C:\Users\debapriya.das\Desktop> python .\hashcode_muncher.py C:\Users\debapriya.das\Desktop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment