Edu*_*scu 10 python encryption zip zipfile python-2.7
我使用python的标准库zipfile来测试存档:
zf = zipfile.ZipFile(archive_name)
if zf.testzip()==None: checksum_OK=True
Run Code Online (Sandbox Code Playgroud)
我得到这个运行时异常:
File "./packaging.py", line 36, in test_wgt
if zf.testzip()==None: checksum_OK=True
File "/usr/lib/python2.7/zipfile.py", line 844, in testzip
f = self.open(zinfo.filename, "r")
File "/usr/lib/python2.7/zipfile.py", line 915, in open
"password required for extraction" % name
RuntimeError: File xxxxx/xxxxxxxx.xxx is encrypted, password required for extraction
Run Code Online (Sandbox Code Playgroud)
如果zip是加密的,在运行testzip()之前如何测试?我没有发现捕获的异常会使这项工作变得更简单.
Zac*_*amm 12
快速浏览一下zipfile.py库代码,可以检查ZipInfo类的flag_bits属性,看看文件是否加密,如下所示:
zf = zipfile.ZipFile(archive_name)
for zinfo in zf.infolist():
is_encrypted = zinfo.flag_bits & 0x1
if is_encrypted:
print '%s is encrypted!' % zinfo.filename
Run Code Online (Sandbox Code Playgroud)
检查是否设置了0x1位是zipfile.py源如何查看文件是否加密(可以更好地记录!)你可以做的一件事是从testzip()捕获RuntimeError然后遍历infolist()和看看zip中是否有加密文件.
你也可以这样做:
try:
zf.testzip()
except RuntimeError as e:
if 'encrypted' in str(e):
print 'Golly, this zip has encrypted files! Try again with a password!'
else:
# RuntimeError for other reasons....
Run Code Online (Sandbox Code Playgroud)