如何检查zip文件是否使用python的标准库zipfile加密? [英] How to check if a zip file is encrypted using python's standard library zipfile?

查看:65
本文介绍了如何检查zip文件是否使用python的标准库zipfile加密?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using python's standard library, zipfile, to test an archive:

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

我收到了此运行时异常:

And I am getting this Runtime exception:

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

在运行testzip()之前,如何测试zip是否已加密?我没有发现可以使这项工作变得更简单的异常.

How can I test, before I run testzip(), if the zip is encrypted? I didn't found an exception to catch that would make this job simpler.

推荐答案

快速浏览zipfile.py库代码显示,您可以检查ZipInfo类的flag_bits属性以查看文件是否已加密,如下所示:

A quick glance at the zipfile.py library code shows that you can check the ZipInfo class's flag_bits property to see if the file is encrypted, like so:

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

检查zipfile.py源如何查看文件是否已加密(可能会更好地进行记录),以查看是否设置了0x1位.您可以做的一件事是从testzip()捕获RuntimeError,然后遍历信息列表(),查看zip中是否有加密文件.

Checking to see if the 0x1 bit is set is how the zipfile.py source sees if the file is encrypted (could be better documented!) One thing you could do is catch the RuntimeError from testzip() then loop over the infolist() and see if there are encrypted files in the zip.

您还可以执行以下操作:

You could also just do something like this:

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....

这篇关于如何检查zip文件是否使用python的标准库zipfile加密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆