Zip file password cracking with Python and Hack

1. Required libraries:

**import zipfile<br>**import optparse<br>**from threading import Thread<br><br>(1) zipfile:<br>1.1 zipfile.ZipFile(fileName[, mode[, compression[, allowZip64]]])<br>There is no doubt about fileName.<br>mode is the same as general file operations, 'r' means to open an existing read-only ZIP file; 'w' means to clear and open a write-only ZIP file, or create a write-only ZIP file;' a' means to open a ZIP file and add content.<br>compression indicates the compression format, and there are only 2 optional compression formats: ZIP_STORE; ZIP_DEFLATED. ZIP_STORE is the default, which means no compression; ZIP_DEFLATED means compression, if you don't know what is deflated, then it is recommended that you make up for it.<br>When allowZip64 is True, it means that 64-bit compression is supported. Generally speaking, this option will be used when the compressed file is larger than 2G; by default, this value is False, because the Unix system does not support it.<br>1.2 zipfile. close()<br>Seriously, there's not much to say about this one, if anything, that any file you write to won't actually be written to disk until it's closed.<br>1.3 zipfile.write(filename[, arcname[, compress_type]])<br>acrname is the name of the file in the compressed file, by default it is the same as filename<br>compress_type exists because zip files allow files to be compressed to have different compression types.<br>1.4 zipfile. extractall([path[, member[, password]]])<br>path to decompress directory, nothing to say<br>member needs to decompress the list of file names<br>password This option is required when the zip file has a password<br>For simple applications, this much is enough.<br><br><br>(2) optparse:

Python has two built-in modules for handling command-line arguments:

One is getopt, which is also mentioned in the book “Deep in python”, which can only simply handle command line parameters;

The other is optparse, which is powerful and easy to use, and can easily generate standard, Unix/Posix-compliant command-line instructions.

Simple process

**First, you must import the OptionParser class to create an OptionParser object:

Python code

Favorite code

  1. from optparse import OptionParser
  2. […]
  3. parser = OptionParser()

**Then, use add_option to define command-line arguments:

Python code

Favorite code

  1. parser.add_option(opt_str, …,
  2. attr=value, …)

**Each command line parameter is composed of parameter name string and parameter attribute. For example, -f or –file are long and short parameter names respectively:

Python code

Favorite code

  1. parser. add_option(“-f”, “–file”, …)

**Finally, once you have defined all command line arguments, call parse_args() to parse the program’s command line:

Python code

Favorite code

  1. (options, args) = parser. parse_args()

**Note: You can also pass a list of command-line arguments to parse_args(); otherwise, sys.argv[:1] is used by default.

The two values returned by parse_args():

  • options, which is an object (optpars.Values) that holds command line parameter values. As long as you know the command-line parameter name, such as file, you can access its corresponding value: options.file .
  • args, which is a list of positional arguments.

Actions

action is one of the parameters of the parse_args() method, which instructs optparse what to do when it parses a command-line argument. Actions has a set of fixed values to choose from, the default is ‘store ‘, which means to save the command line parameter values in the options object.

example

Python code

Favorite code

  1. parser.add_option(“-f”, “–file”,
  2. action=”store”, type=”string”, dest=”filename”)
  3. args = [“-f”, “foo.txt”]
  4. (options, args) = parser. parse_args(args)
  5. print options. filename

In the end, “foo.txt” will be printed.

When optparse parses to ‘-f’, it will continue to parse the following ‘foo.txt’, and then save ‘foo.txt’ to options.filename. When parser.args() is called, options.filename will be ‘foo.txt’.

You can also specify other values for the type parameter in the add_option() method, such as int or float, etc.:

Python code

Favorite code

  1. parser.add_option(“-n”, type=”int”, dest=”num”)

By default, type is ‘string’. Also as shown above, long parameter names are optional. In fact, the dest parameter is also optional. If no dest parameter is specified, the value of the options object will be accessed with the name of the command line parameter.

There are also two other forms of store: store_true and store_false , which are used to handle the case where there is no value after the command line parameter. Such as -v, -q and other command line parameters:

Python code

Favorite code

  1. parser.add_option(“-v”, action=”store_true”, dest=”verbose”)
  2. parser.add_option(“-q”, action=”store_false”, dest=”verbose”)

In this way, when parsing to ‘-v’, options.verbose will be assigned a True value, otherwise, when parsing to ‘-q’, it will be assigned a False value.

Other actions values include: store_const , append , count , callback .

(3)Thread: Multi-thread processing<br>The Thread class represents the activity of a single running thread of control. We have two ways to specify this activity, either through a callable object's constructor, or by overriding the subclass run() method. No other methods should be overridden in subclasses. In other words, only override the __init__() and run() methods of this class.<br>        Once the Thread object is created, the activity of this object must be started through the thread's start() method. This will invoke the run() method in a separate thread of control.<br>        Once a thread's activity begins, the thread's state is "alive". The "alive" state ends when the run() method ends. We can also directly run the is_alive() method to judge the state of the process when "alive"<br>        A thread can call the join() method of another thread. This is called blocking the calling thread until its join() method is called thread termination.<br>       The name of a thread is passed through the constructor, and can also be modified or read through the name attribute.<br>        A thread can be marked as a daemon thread (daemon thread), and this marked thread will only exit when the python program exits. Its initial value is inherited when the thread is created. This flag can be set by daemon or daemone constructor variables.<br>        Tip: The daemon thread is interrupted immediately when the program is closed. It will not be properly released. If you want your thread to stop gracefully. Either make it non-daemonic or use some proper signaling mechanism.<br>Commonly used methods and variables in Thread:<br>1. start()<br>Start thread activity.<br>2. run()<br>This method describes the activity of the thread, and we can override this method in subclasses.<br>3. join()<br>    The join() method is also provided in python's Thread class, so that one thread can wait for another thread to finish executing before continuing to run. This method can also set a timeout parameter to avoid endless waiting. Because two threads complete sequentially and look like one thread, it is called thread merging.<br>      Set the timeout by passing a parameter to join, that is, join will not block the process after the specified time. In the actual application test, it is found that not all threads end within the timeout period, but the sequential execution checks whether the timeout timeout occurs within the time_out period. For example, if the timeout period is set to 2s, the previous thread is not completed. After the thread executes the join, a timeout of 2s will be set from the end time of the previous thread.<br>4. name()<br>5. getname(0<br>6. setname()<br>7.ident()<br>8.is_alive()<br>9. daemon<br>A Boolean value indicating whether this thread is a damemon thread (TRUE) or not (FALSE). The start() call must be set before this, otherwise an error will occur during runtime. Its initial value is inherited from the creating thread; the main thread is not a daemon thread, so all threads created in daemon=false mainthread default.<br>No live non-daemon threads leave when the entire Python program exits.<br>10. isDaemon()<br>11. setDaemon()<br><br><br><br><br><br><br>The source code of the Zip file password cracking machine:
import zipfile<br>import optparse<br>from threading import Thread<br>def extractFile(zFile, password):<br>    try:<br>        zFile. extractall(pwd=password)<br>        print('[ + ] Found password' + password + '\\
')<br>    except:<br>        pass<br>def main():<br>    parser=optparse.OptionParser("usage%prog" + \<br>                                 "-f <zipfile> -d <dictionary>")<br>    parser.add_option('-f', dest='zname', type='string',\<br>                      help='specify dictionary file')<br>    parser.add_option('-d', dest='dname', type='string',\<br>                      help='specify diction file')<br>    (options, args) = parser. parse_args()<br><br>    if(options. zname==None) | (options. dname==None):<br>        print(parser. usage)<br><br>        exit(0)<br>    else:<br>        zname=options.zname<br>        dname=options.dname<br>    zFile = zipfile. ZipFile(zname)<br>    passFile=open(dname)<br>    for line in passFile. readline():<br>        password=line.strip('\\
')<br>        t=Thread(target=extractFile,args=(zFile,password))<br>        t. start()<br>if __name__=='__main__':<br>    main()<br><br><br>
<br><br>**It has not been run, and it finally ran out this afternoon: mainly using the method of print() line by line, and found:<br><br>1. There is no big problem with the main function, that is, during the for loop:
for line in passFile.readline(): This is wrong<br>The readline() function only reads one letter, and the readlines() function is needed to read a complete letter, only one "s" is missing! ! ! ! !<br><br>2. The file object provides three "read" methods: .read(), .readline() and .readlines(). Each method can accept a variable to limit the amount of data read each time, but they generally don't use variables. .read() reads the entire file at a time, it is usually used to put the contents of the file into a string variable. While .read() produces the most direct string representation of the file contents, it is unnecessary for sequential line-oriented processing, and impossible if the file is larger than available memory. 
<br>3. readlines() example

fh = open( ‘c:\autoexec.bat’) for line in fh.readlines(): print line The difference between.readline() and .readlines() is that the latter reads the entire file at once , like .read(). .readlines() automatically parses the file contents into a list of lines that can be processed by Python’s for… in … construct. On the other hand, .readline() reads one line at a time and is generally much slower than .readlines() . .readline() should only be used when there is not enough memory to read the entire file at once.

Write:

writeline() is a newline after the output, and the next write will be written on the next line. write() means that the cursor will not wrap at the end of the line after output, and the next time you write, it will continue to write this line

The functions that this experiment focuses on:

1.ZipFile.extract(member[, path[, pwd]])

Unzip the specified file in the zip archive to the current directory. The parameter member specifies the name of the file to be decompressed or the corresponding ZipInfo object; the parameter path specifies the folder where the parsed file is saved; the parameter pwd is the decompression password. The following example decompresses all the files in txt.zip stored in the root directory of the program to the D:/Work directory:

Compress all files in the zip archive to the current directory. The default value of the parameter members is a list of all file names in the zip file, or you can set it yourself to select the file name to be decompressed.

2. strip() function:


The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill tree advanced grammar file 258841 people are studying systematically