如何使用python的标准库zipfile检查zip文件是否加密?

时间:2012-08-20 13:18:47

标签: python zip python-2.7 zipfile encryption

我正在使用python的标准库zipfile来测试存档:

zf = zipfile.ZipFile(archive_name)
if zf.testzip()==None: checksum_OK=True

我得到了这个运行时异常:

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

如果zip是加密的,在运行testzip()之前如何测试?我没有发现一个例外,可以使这项工作更简单。

2 个答案:

答案 0 :(得分:11)

快速浏览一下the zipfile.py library code,可以检查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

检查是否设置了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....

答案 1 :(得分:0)

如果你想捕捉异常,你可以这样写:

zf = zipfile.ZipFile(archive_name)
try:
    if zf.testzip() == None:
        checksum_OK = True
except RuntimeError:
    pass