Skip to content

Instantly share code, notes, and snippets.

@rondreas
Last active Sep 24, 2019
Embed
What would you like to do?
#!/usr/bin/python3
import hashlib, sys
"""
Command line tool to get checksums in python.
Supply filepath for file to process, and which hash
method to use.
"""
def checksum(f, sh='md5', cmp=''):
''' Hash file f using method sh. Possible to compare
hexdigest with precalculated hash cmp. '''
try:
try:
m = hashlib.new(sh)
except(ValueError):
print("Invalid hashing algorithm: {}".format(sh))
return
with open(f, 'rb') as infile:
byte = infile.read(128)
while byte:
m.update(byte)
byte = infile.read(128)
if cmp:
# Strip away spaces and make all chars lowercase.
cmp = cmp.replace(' ','').lower()
# Compare digest with given precomputed hash to check
# for a match.
if(m.hexdigest() == cmp):
return True
else:
return False
print(m.hexdigest())
except(FileNotFoundError):
print("Could not find file: {}".format(f))
if __name__ == '__main__':
if len(sys.argv) == 2:
checksum(sys.argv[1])
elif len(sys.argv) == 3:
checksum(sys.argv[1], sys.argv[2])
elif len(sys.argv) == 4:
checksum(sys.argv[1], sys.argv[2], sys.argv[3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment