Python zip暴力破解

网上下到带有密码的zip文件,但是又没有给出密码,着实头疼,不如自动动手用python写一个zip暴力破解程序。

阅读文本前推荐您先浏览之前的文章:Python 创建黑客字典

0x00 前提

  1. python提供了对zip文件的操作库zipfile。其中 ZipFile 类中的 extractall() 方法提供了 pwd 参数作为 zip 文件的密码。更多关于 zipfile

  2. python 中的 optparse 模块可以用来处理命令行参数。其主要使用流程:首先,必须 import OptionParser 类,创建一个 OptionParser 对象,然后,使用 add_option 来定义命令行参数,每个命令行参数就是由参数名字符串和参数属性组成的。最后,一旦你已经定义好了所有的命令行参数,调用 parse_args() 来解析程序的命令行。更多关于 optparse

作为测试,我们将我们写一个名为 unzip.py 的脚本来破解密码,在它的同级目录下存在测试文件 test.zip 和字典文件 dict.txt(关于字典文件的创建),其中 zip 文件的密码为 123456 。

0x01 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import zipfile
import optparse

def extractFile(zFile, password):
try:
zFile.extractall(pwd=password)
print '[+] Found password ' + password + '\n'
return True
except:
return False

def main():
parser = optparse.OptionParser("usage%prog -f <zipfile> -d <dictionary>")
parser.add_option('-f', dest='zname', type='string', \
help='specify zipfile file')
parser.add_option('-d', dest='dname', type='string', \
help='specify dictionary file')
(options, args) = parser.parse_args()
if (options.zname == None) | (options.dname == None):
print parser.usage
exit(0)
else:
zname = options.zname
dname = options.dname
zFile = zipfile.ZipFile(zname)
passFile = open(dname)
for line in passFile.readlines():
password = line.strip('\n')
if extractFile(zFile, password):
break

if __name__ == '__main__':
main()
0%