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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
""" 计算文件哈希值, 如果给出了文件哈希值,会校验哈希值是否匹配 """
import argparse import hashlib import os
class ProgressBar: """ 进度条 """ MAX_LENGTH = 25 STYLE_UNDO = '*' STYLE_DONE = '=' def __init__(self, total=100, prefix="Loop"): self.cur = 0 self.total = total self.prefix = prefix def restart(self, cur=None, total=None): if cur is not None: assert isinstance(cur, int), "Error type for cur: {}".format(cur) self.cur = cur if total is not None: assert isinstance(total, int), "Error type for total: {}".format(total) self.total = total
def step(self, val=1): if self.cur >= self.total: return self.cur += val undo = int(self.MAX_LENGTH * min(self.cur / self.total, 1)) print("{} [{}{}{}] {:>5.2f}%".format(self.prefix, self.STYLE_DONE * (max(1, undo) - 1), '>', self.STYLE_UNDO * (self.MAX_LENGTH - undo), self.cur / self.total * 100), end='\r')
if __name__ == '__main__': parser = argparse.ArgumentParser(description="To check hash value for file") parser.add_argument("-f", "--filename", nargs='+', default=[], type=str, help='File name (default: all file in current path)') parser.add_argument("-v", "--hash", nargs='+', default=None, type=str, help='Hash value for file') parser.add_argument("-alg", "--algorithm", default='md5', choices=hashlib.algorithms_available, type=str, help="Hash algorithm") args = parser.parse_args()
filelist = args.filename if not filelist: filelist = list(filter(os.path.isfile, os.listdir())) hashlist = args.hash if hashlist is None: hashlist = [None for _ in filelist] assert len(hashlist) == len(filelist), "Unmatch l file number({}) and hash val number{}".format(len(hashlist), len(filelist))
alg = args.algorithm for filename, hashval in zip(filelist, hashlist): if alg == 'md5': hashobj = hashlib.md5() elif alg == 'sha256': hashobj = hashlib.sha256() else: hashobj = hashlib.new(args.algorithm) pb = ProgressBar(total=os.stat(filename).st_size, prefix=filename) with open(filename, 'rb') as f: for line in f: hashobj.update(line) pb.step(len(line)) print(" " * 100, end='\r') out = hashobj.hexdigest() if hashval is None: print("{} value of {} is {}".format(alg, filename, out)) else: if out == hashval: print("{} value of {} is match ({})".format(alg, filename, out)) else: print("ERROR: {} value of {} is not match (true value: {})".format(alg, filename, out))
input("\nFinish!\n")
|