Created
February 23, 2012 18:44
-
-
Save brantfaircloth/1894285 to your computer and use it in GitHub Desktop.
Check a list of files against a list of openssl checksums (sha1 and md5)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
File: check_sum.py | |
Author: Brant Faircloth | |
Created by Brant Faircloth on 23 February 2012 10:02 PST (-0800) | |
Copyright (c) 2012 Brant C. Faircloth. All rights reserved. | |
Description: Check a list of files against hashes. | |
License: http://www.opensource.org/licenses/BSD-3-Clause | |
On sending end, generate sha1 hashes like so: | |
for i in *.gz; do openssl sha1 $i >> file-with-sha1-checksums.txt; done | |
Send that file, along with files being shipped to recipient. On receving end | |
recipient validates with: | |
python check_sum.py file-with-sha1-checksums.txt | |
/path/to/directory/to/validate | |
""" | |
import os | |
import sys | |
import re | |
import glob | |
import hashlib | |
import argparse | |
def get_args(): | |
parser = argparse.ArgumentParser(description='''Validate checksums given a | |
list''') | |
parser.add_argument('checksums', nargs='?', type=argparse.FileType('r'), | |
default=sys.stdin) | |
parser.add_argument('dir', nargs='?', default=sys.stdout) | |
parser.add_argument('--md5', action='store_true', default = False) | |
return parser.parse_args() | |
def hashfile(afile, hasher, blocksize=65536): | |
""" slightly modified from @Omnifarious in stackexchange thread: | |
http://bit.ly/erSQcW | |
""" | |
buf = afile.read(blocksize) | |
while len(buf) > 0: | |
hasher.update(buf) | |
buf = afile.read(blocksize) | |
return hasher.hexdigest() | |
def main(): | |
args = get_args() | |
cs = {} | |
if not args.md5: | |
regex = re.compile("SHA1\((.*)\)=\s(.*)") | |
else: | |
regex = re.compile("MD5\((.*)\)=\s(.*)") | |
for line in args.checksums: | |
ls = line.strip() | |
match = regex.search(ls) | |
cs[match.groups()[0]] = match.groups()[1] | |
print "{0:30} {1:4}".format('Filename', 'Status') | |
print '-' * 37 | |
for fname in glob.glob(os.path.join(args.dir, '*.*')): | |
if args.checksums.name in fname: | |
pass | |
else: | |
if not args.md5: | |
hsh = hashfile(file(fname, 'r'), hashlib.sha1()) | |
else: | |
hsh = hashfile(file(fname, 'r'), hashlib.md5()) | |
assert cs[os.path.basename(fname)] == hsh, "File sha1 hashes do not match""" | |
print "{0:30} {1:4}".format(os.path.basename(fname), '[ok]') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment