Welcome, guest | Sign In | My Account | Store | Cart

I'm used to having the md5sum utility on Linux systems, so I was surprised that Mac OS-X doesn't seem to have it. Rather than finding and compiling the C code, I took advantage of the fact that 10.3 includes Python, and rolled my own.

Python, 46 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python

## md5hash
##
## 2004-01-30
##
## Nick Vargish
##
## Simple md5 hash utility for generating md5 checksums of files. 
##
## usage: md5hash <filename> [..]
##
## Use '-' as filename to sum standard input.

import md5
import sys

def sumfile(fobj):
    '''Returns an md5 hash for an object with read() method.'''
    m = md5.new()
    while True:
        d = fobj.read(8096)
        if not d:
            break
        m.update(d)
    return m.hexdigest()


def md5sum(fname):
    '''Returns an md5 hash for file fname, or stdin if fname is "-".'''
    if fname == '-':
        ret = sumfile(sys.stdin)
    else:
        try:
            f = file(fname, 'rb')
        except:
            return 'Failed to open file'
        ret = sumfile(f)
        f.close()
    return ret


# if invoked on command line, print md5 hashes of specified files.
if __name__ == '__main__':
    for fname in sys.argv[1:]:
        print '%32s  %s' % (md5sum(fname), fname)

This mainly useful for systems without an included "md5sum" utility, like OS-X and Win32. It shows just how useful the batteries included philosophy of Python can be, since it leverages the md5 module.

3 comments

gyro funch 17 years, 10 months ago  # | flag

Similar utility is included in the distribution. There is a script with a similar function included in the Python distribution:

..\Python22\Tools\scripts\md5sum.py

Albert Lin 17 years, 10 months ago  # | flag

Use the "md5" command on Mac OS X. FYI, Mac OS X does have a built-in md5 checksum command. It is called "md5".

It's in /sbin/md5 on my copy of Mac OS 10.2.8. I'm pretty sure it's there by default, but perhaps you need to install the Developer Tools CD for it to be there.

Kevin L 13 years, 1 month ago  # | flag

Neat! Just what I was looking for. have added the functions to a script that recursively traverse the dir and sub dir and outputs the filenames and directory. and now the md5 sums :)

http://kevinl.wordpress.com/2008/11/07/python-script-to-inventorise-your-ab1-files-with-md5sums/