简体   繁体   中英

How to check if a zip file is encrypted using python's standard library 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

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.

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

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

If you want to catch an exception, you can write this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM