sha1sum rewritten in python using openssl

November 5th, 2009

I like how I can use the sha1sum tool on my Linux boxes to create a file with checksums of a collection of files and then use the tool again to verify the files against the checksums.

I've been missing that functionality on my Mac, so I wrote a small wrapper to the openssl command that provide the same basic functionality using Python. Python is really handy when it comes to writing small scripts like that does some string handling and calls other programs and since the basic checksumming functionality already is available in the openssl package it simple, short and neat.

As usual, feel free to use this any way you want.

 
#!/usr/bin/python
 
import subprocess
import sys
 
def checksum_file(filename):
    sp = subprocess.Popen(["/usr/bin/openssl", "sha1", filename],
                          stdout=subprocess.PIPE)
    retval = sp.communicate()[0]
    return retval[retval.find("= ") + 2:-1]
 
def verify(checksumfile):
    f = open(checksumfile, "r")
    for line in f:
        line = line[:-1]
		(sha1, fn) = line.split("  ")
		calc = checksum_file(fn)
		if calc != sha1:
            print "%s: FAILED" % fn
            sys.exit(1)
        else:
            print "%s: OK" % fn
 
def usage():
    print "Usage: sha1sum [-c CHECKSUM_FILE] [FILE]..."
    sys.exit(1)
 
if __name__ == '__main__':
    if len(sys.argv) == 1:
        usage()
	if sys.argv[1] == '-c':
        if len(sys.argv) != 3:
            usage()
        verify(sys.argv[2])
    else:
        for f in sys.argv[1:]:
            print "%s  %s" % (checksum_file(f), f)
 

Trackback URI | Comments RSS

Leave a Reply

Name (required)

Email (required)

Website

Speak your mind