我一直在尝试实现一个非常简单的脚本,提取受密码保护的zip文件。 我创建了一个简单的zip文件(test.zip),密码为“1234”,包含2个文本文件(1.txt,2.txt),我写了这个脚本:
import zipfile
PASSWORD = "1234"
zip = zipfile.ZipFile("test.zip", "r")
zip.setpassword(PASSWORD)
zip.extractall()
zip.close()
我收到以下运行时错误:
Traceback (most recent call last):
File "test.py", line 7, in <module>
zip.extractall()
File "/usr/lib/python2.7/zipfile.py", line 962, in extractall
self.extract(zipinfo, path, pwd)
File "/usr/lib/python2.7/zipfile.py", line 950, in extract
return self._extract_member(member, path, pwd)
File "/usr/lib/python2.7/zipfile.py", line 993, in _extract_member
source = self.open(member, pwd=pwd)
File "/usr/lib/python2.7/zipfile.py", line 934, in open
raise RuntimeError("Bad password for file", name)
RuntimeError: ('Bad password for file', <zipfile.ZipInfo object at 0x1f3f2a8>)
我尝试使用“zip.namelist()”和“extract()”方法迭代+指定确切的参数如下:
zip.extract(<file_name>, path=<path>, pwd=<password>)
没有运气:( 我知道“extractall()”的安全问题,在我的完整代码中,我将在提取过程之前进行验证,我只想弄清楚我做错了什么?
提前感谢您的帮助!
答案 0 :(得分:11)
如评论中所示,您的加密模式可能存在问题。 使用7-zip创建使用AES-256的zip文件我得到的错误与你的相同。使用ZypCrypto加密,它可以正常工作。
PyCrust 0.9.8 - The Flakiest Python Shell
Python 2.6.7 (r267:88850, Jun 27 2011, 13:20:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import zipfile
>>> psw = "abcd"
#with zipcrypto encryption
>>> path= "C:/Users/joaquin/Desktop/zipcrypto.zip"
>>> zip = zipfile.ZipFile(path, "r")
>>> zip.setpassword(psw)
>>> zip.extractall("C:/Python26")
>>> zip.close()
#with AES-256 encryption
>>> path= "C:/Users/joaquin/Desktop/aes256.zip"
>>> zip = zipfile.ZipFile(path, "r")
>>> zip.setpassword(psw)
>>> zip.extractall("C:/Python26")
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python26\lib\zipfile.py", line 938, in extractall
self.extract(zipinfo, path, pwd)
File "C:\Python26\lib\zipfile.py", line 926, in extract
return self._extract_member(member, path, pwd)
File "C:\Python26\lib\zipfile.py", line 969, in _extract_member
source = self.open(member, pwd=pwd)
File "C:\Python26\lib\zipfile.py", line 901, in open
raise RuntimeError("Bad password for file", name)
RuntimeError: ('Bad password for file', <zipfile.ZipInfo object at 0x00000000042B3948>)
>>>
此问题(仅支持传统PKWARE加密方法的zipfile)已报告为feature request for python 3.2
答案 1 :(得分:6)
同意eryksun&amp;华金
7z l -slt test.zip | grep Method
将显示使用的压缩方法。
7z a -p1234 -mem=ZipCrypto test.zip 1.txt 2.txt
将创建一个兼容python zipfile的zip。
7z a -p1234 -mem=AES128 test.zip 1.txt 2.txt
将创建AES加密zip。