optparser模块:
为脚本传递命令参数。
初始化:
- 带 Usage 选项(-h 的显示内容 Usage:):
>>> from optparse import OptionParser >>> usage = "usage %prog -f <zipfile> -d <dictionary>" # %prog为Py文件名
>>> parser=OptionParser(usage) #这里为类添加了参数usage >>> parser.print_help() Usage: usage -f <zipfile> -d <dictionary> Options: -h, --help show this help message and exit
- 不带 Usage 选项:
>>> parser = OptionParser()
添加选项:
add_option:()
- action: 验证输入数据类型是否和type 匹配,并将符合要求的这个参数存储到dest变量中。有以下几个属性:
store 默认值。
store_false 标记 配合下边的那个store_true来进行代码的“标记”,辅助流程控制。
store_true 标记。
- type : 参数数据类型,如-f,-d等的接下来的那个参数的数据类型,有string,int,float等等。
- dest : 保存临时变量,其值可以作为 options 的属性进行访问。存储的内容就是如-f,-d 等紧挨着的那个参数内容。
- default : 给dest的默认值。
- help: 提供用户友好的帮助信息,解释add_option方法的功能。
>>>parser.add_option('-f', '--file', dest='zname', type='string', help='zip file name') >>>parser.add_option('-d', '--dictionary', dest='dname', type='string', help=' password dictionary')
ZIP爆破脚本:
1 # -*- coding: utf-8 -*- 2 import zipfile 3 import optparse 4 from threading import Thread 5 6 7 def extractFile(zFile, password): #extractFile()函数 寻找与ZIP文件匹配的密码 8 try: 9 zFile.extractall(pwd = password) 10 print '[+] Found password ' + password + '\n' 11 except: 12 pass 13 14 15 def main(): 16 parser = optparse.OptionParser("usage %prog "+ "-f <zipfile> -d <dictionary>") 17 parser.add_option('-f', '--file', dest='zname', type='string', help='The zip file which you want to crack') 18 parser.add_option('-d', '--dictionary', dest='dname', type='string', help='The password dictionary') 19 (options, args) = parser.parse_args() #调用 parse_args() 来解析程序的命令行 20 if (options.zname == None) | (options.dname == None): 21 print parser.usage 22 exit(0) 23 else: 24 zname = options.zname 25 dname = options.dname 26 27 zFile = zipfile.ZipFile(zname) 28 passFile = open(dname) 29 30 for line in passFile.readlines(): #读取字典文件 31 password = line.strip('\n') 32 t = Thread(target = extractFile, args =(zFile, password)) #使用线程 33 t.start() 34 35 36 if __name__ == '__main__': 37 main()