Skip to content

Instantly share code, notes, and snippets.

@rondreas
Last active September 24, 2019 15:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondreas/71b4cabb4d54a329d356a5a77f638ed0 to your computer and use it in GitHub Desktop.
Save rondreas/71b4cabb4d54a329d356a5a77f638ed0 to your computer and use it in GitHub Desktop.
#!/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