方法一:先实例化一个对象,再使用update做校验,最后十六进制查看hexdigest
In [3]: import hashlib
In [5]: md5 = hashlib.md5()
In [6]: md5.update("a")
In [7]: md5.hexdigest()
Out[7]: '0cc175b9c0f1b6a831c399e269772661'
与shell下一致,-n 不加换行符时
[root@huangzp3 python]# echo "a"|md5sum
60b725f10c9c85c70d97880dfe8191b3 -
[root@huangzp3 python]# echo -n "a"|md5sum
0cc175b9c0f1b6a831c399e269772661 -
说明:更新,实际为ab\n的值
In [8]: md5.update("b\n")
In [9]: md5.hexdigest()
Out[9]: 'daa8075d6ac5ff8d0c6d4650adb4ef29'
对比shell,哈希值一样
[root@huangzp3 python]# echo "ab"|md5sum
daa8075d6ac5ff8d0c6d4650adb4ef29 -
方法二:字符串短时,直接调用
In [10]: hashlib.md5("hello").hexdigest()
Out[10]: '5d41402abc4b2a76b9719d911017c592'
脚本:
#!/usr/bin/env python import sys import hashlib import codecs def getMd5(f): md5 = hashlib.md5() with codecs.open(f) as fd: while True: data = fd.read(4096) if data: md5.update(data) #每读一次,获取一次md5值,MD5值累加 else: break return md5.hexdigest() if __name__ == "__main__": try: print getMd5(sys.argv[1]) except IndexError: print ("%s follow a argument" % __file__)
运行结果:
[root@huangzp3 python]# python 01.py 1.py
e796a8f418fa90d7e4f0a162119f114a
[root@huangzp3 python]# cat 1.py |md5sum
e796a8f418fa90d7e4f0a162119f114a -
原文:http://blog.51cto.com/huangzp/2060269