TransWikia.com

Python extract files from zip

Stack Overflow Asked by The X and D on December 22, 2021

trying to make a simple password brute force to unzip a .zip archive in python, im using permutations to try every possibility with 2 caracteres(my idea is use more permutations in the future), and also i set up a .zip file with 2 characteres password. But my program just dont extract the files from the zip.

import zipfile
from itertools import permutations
import re

z1 = input("Enter with file path+filename.zip:")
z = zipfile.ZipFile(z1)

caracteres = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

for i in permutations(caracteres,2): 
    i = re.sub(r'W',"",str(i))
    print(i)
    password = i.encode()
    try:     
        z.open(z1, mode='r')   
        z.extractall(pwd=password)
        print ("pass="+i+"n")
        exit(0)
    except Exception:
        pass

One Answer

Permutations assumes that the objects in the list can only be used once. So given your list of characters, passwords like "aa" can never appear. If that happened to be your test password, it would never match. itertools.product may be a better choice.

>>> list(itertools.permutations("ABC", 2))
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
>>> list(itertools.product("ABC", repeat=2))
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]

Your next problem is that you don't seem to be calling z.open() properly. This would be used to extract a particular file from the archive. But you're passing in z1, which is the zipfile object, not a name. Further, you're not supplying a password. So this call will fail every time, preventing the later extraction from starting. I think you need to get rid of the z.open() line entirely.

Answered by BowlOfRed on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP