我如何使用Python计算文件系统目录的哈希值? [英] How can I calculate a hash for a filesystem-directory using Python?
本文介绍了我如何使用Python计算文件系统目录的哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
m = hashlib.md5()
with open(calculator.pdf,'rb')为fh:
,而True:
data = fh.read(8192)
如果不是数据:
break
m.update(data)
hash_value = m.hexdigest()
print hash_value
当我在一个文件夹文件夹上试过时我得到了
IOError:[Errno 13]权限被拒绝:文件夹
我如何计算文件夹的散列值?
解决方案
配方提供了一个很好的功能来完成你所要求的功能。我已经修改它以使用MD5散列,而不是SHA1,因为您原来的问题是要求
def GetHashofDirs(directory,
import hashlib,os
SHAhash = hashlib.md5()
如果不是os.path.exists(目录):
返回-1
尝试:
用于root,dirs,os.walk(目录)中的文件:
用于文件中的名称:
if verbose == 1:
print'哈希',命名
filepath = os.path.join(root,names)
try:
f1 = open(filepath,'rb')
除外:
#由于某些原因,您无法打开该文件
f1.close()
continue
while 1:
#以小块形式读取文件
buf = f1.read(4096)
如果不是buf:break
SHAhash.update(hashlib.md5(buf).hexdigest())
f1.close()
除外:
导入追踪
#打印堆栈
traceback.print_exc()
返回-2
返回SHAhash.hexdigest()
您可以像这样使用它:
print GetHashofDirs('folder_to_hash',1)
输出看起来像这样,因为它散列每个文件:
...
Hashing file1.cache
Hashing text.txt
Hashing library.dll
Hashing vsfile.pdb
Hashing prog.cs
5be45c5a67810b53146eaddcae08a809
来自此函数调用的返回值作为哈希返回。在这种情况下, 5be45c5a67810b53146eaddcae08a809
I'm using this code to calculate hash value for a file:
m = hashlib.md5()
with open("calculator.pdf", 'rb') as fh:
while True:
data = fh.read(8192)
if not data:
break
m.update(data)
hash_value = m.hexdigest()
print hash_value
when I tried it on a folder "folder"I got
IOError: [Errno 13] Permission denied: folder
How could I calculate the hash value for a folder ?
解决方案
This Recipe provides a nice function to do what you are asking. I've modified it to use the MD5 hash, instead of the SHA1, as your original question asks
def GetHashofDirs(directory, verbose=0):
import hashlib, os
SHAhash = hashlib.md5()
if not os.path.exists (directory):
return -1
try:
for root, dirs, files in os.walk(directory):
for names in files:
if verbose == 1:
print 'Hashing', names
filepath = os.path.join(root,names)
try:
f1 = open(filepath, 'rb')
except:
# You can't open the file for some reason
f1.close()
continue
while 1:
# Read file in as little chunks
buf = f1.read(4096)
if not buf : break
SHAhash.update(hashlib.md5(buf).hexdigest())
f1.close()
except:
import traceback
# Print the stack traceback
traceback.print_exc()
return -2
return SHAhash.hexdigest()
You can use it like this:
print GetHashofDirs('folder_to_hash', 1)
The output looks like this, as it hashes each file:
...
Hashing file1.cache
Hashing text.txt
Hashing library.dll
Hashing vsfile.pdb
Hashing prog.cs
5be45c5a67810b53146eaddcae08a809
The returned value from this function call comes back as the hash. In this case, 5be45c5a67810b53146eaddcae08a809
这篇关于我如何使用Python计算文件系统目录的哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文