Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gmolveau
GitHub Repository: gmolveau/python_full_course
Path: blob/master/exercices/imperative/zip-bruteforcer/solution_argparse.py
306 views
1
# password = 'a' or 'xiphihumeralis'
2
3
import argparse
4
import logging
5
import os
6
import zipfile
7
8
9
def configure_logging(loglevel):
10
logging.basicConfig(level=loglevel)
11
12
13
def file_exists(filepath):
14
if not os.path.isfile(filepath):
15
raise argparse.ArgumentTypeError(f"{filepath} does not exist")
16
return filepath
17
18
19
def parse_args():
20
parser = argparse.ArgumentParser(description="zip bruteforcer")
21
parser.add_argument(
22
"-v",
23
"--verbose",
24
help="enable verbose mode",
25
action="store_const",
26
dest="loglevel",
27
const=logging.DEBUG,
28
default=logging.INFO,
29
)
30
parser.add_argument(
31
"-f",
32
"--file",
33
dest="protected_zip_path",
34
help="path of the protected zip file",
35
type=file_exists,
36
required=True,
37
)
38
parser.add_argument(
39
"-w ",
40
"--wordlist",
41
dest="wordlist_path",
42
help="path of the wordlist file",
43
type=file_exists,
44
required=True,
45
)
46
return parser.parse_args()
47
48
49
def main(protected_zip_path, wordlist_path):
50
with zipfile.ZipFile(protected_zip_path) as z:
51
with open(wordlist_path) as wordlist_file:
52
for password_line in wordlist_file:
53
password = password_line.strip()
54
try:
55
z.extractall(pwd=password.encode("utf-8"))
56
logging.info(f"password found: {password}")
57
break
58
except zipfile.BadZipFile as e:
59
logging.error(f"the zip file is invalid - {e}")
60
raise e
61
except RuntimeError as e:
62
logging.debug(f"bad password: {password}")
63
64
65
if __name__ == "__main__":
66
args = parse_args()
67
configure_logging(args.loglevel)
68
main(args.protected_zip_path, args.wordlist_path)
69
70