md5sum shell 脚本和 python hashlib.md5 不同

Chr*_*_vr 1 python shell

我正在比较两个不同位置的两个 qcow2 图像文件以查看差异。/opt/images/file.qcow2 /mnt/images/file.qcow2

当我跑

md5sum /opt/images/file.qcow2 
md5sum  /mnt/images/file.qcow2
Run Code Online (Sandbox Code Playgroud)

两个文件的校验和相同

但是当尝试使用以下代码找到 md5sum 时

def isImageLatest(file1,file2):
    print('Checking md5sum of {} {}'.format(file1, file2))

    if os.path.isfile(file1) and os.path.isfile(file2):
        md5File1 = hashlib.md5(file1).hexdigest()
        md5File2 = hashlib.md5(file2).hexdigest()
        print('md5sum of {} is {}'.format(file1, md5File1))
        print('md5sum of {} is {}'.format(file2, md5File2))
    else:
        print('Either {} or {} File not found'.format(file1,file2))
        return False

    if md5File1 == md5File2:
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

它说校验和不一样

更新 文件大小可以为 8 GB

Cyr*_*bil 5

您正在散列文件的路径,而不是内容......

hashlib.md5(file1).hexdigest() # file1 = '/path/to/file.ext'
Run Code Online (Sandbox Code Playgroud)

散列内容:

def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def isImageLatest(file1,file2):
    print('Checking md5sum of {} {}'.format(file1, file2))

    if os.path.isfile(file1) and os.path.isfile(file2):
        md5File1 = md5(file1)
        md5File2 = md5(file2)
        print('md5sum of {} is {}'.format(file1, md5File1))
        print('md5sum of {} is {}'.format(file2, md5File2))
    else:
        print('Either {} or {} File not found'.format(file1,file2))
        return False

    if md5File1 == md5File2:
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

旁注:您可能想使用hashlib.sha1()(使用 unix 的sha1sum)而不是md5它已损坏和已弃用...

编辑:具有各种缓冲区大小的基准测试和md5vs在蹩脚的服务器上sha1 使用100mB随机文件(Atom N2800 @1.86GHz):

???????????????????????????????????????
? Algorithm ?  Buffer ?    Time (s)   ?
???????????????????????????????????????
?    md5sum ?     --- ? 0.387         ?
?       MD5 ?     2?  ? 21.5670549870 ?
?       MD5 ?     2?  ? 6.64844799042 ?
?       MD5 ?     2¹? ? 3.12886619568 ?
?       MD5 ?     2¹² ? 1.82865810394 ?
?       MD5 ?     2¹? ? 1.27349495888 ?
?       MD5 ?   128¹  ? 11.5235209465 ?
?       MD5 ?   128²  ? 1.27280807495 ?
?       MD5 ?   128³  ? 1.16839885712 ?
?   sha1sum ?    ---  ? 1.013         ?
?      SHA1 ?     2?  ? 23.4520659447 ?
?      SHA1 ?     2?  ? 7.75686216354 ?
?      SHA1 ?     2¹? ? 3.82775402069 ?
?      SHA1 ?     2¹² ? 2.52755594254 ?
?      SHA1 ?     2¹? ? 1.93437695503 ?
?      SHA1 ?   128¹  ? 12.9430441856 ?
?      SHA1 ?   128²  ? 1.93382811546 ?
?      SHA1 ?   128³  ? 1.81412386894 ?
???????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

所以md5sumsha1sumpython的实现显示的更快。拥有更大的缓冲区可以提高性能,但在一定限度内(16384似乎是一个很好的权衡(不是太大和效率))。