Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gmolveau
GitHub Repository: gmolveau/python_full_course
Path: blob/master/exercices/imperative/zip-bruteforcer/solution_sysargv.py
306 views
1
import logging
2
import os
3
import sys
4
import zipfile
5
from collections import namedtuple
6
7
8
class UnkownFlagException(Exception):
9
pass
10
11
12
class MissingArgumentException(Exception):
13
pass
14
15
16
class FileNotFoundException(Exception):
17
pass
18
19
20
Args = namedtuple("Args", ["input_filepath", "verbose_mode", "passwords_filepath"])
21
22
23
def configure_logging(loglevel=logging.INFO):
24
logging.basicConfig(level=loglevel)
25
26
27
def check_file_exists(filepath):
28
if not os.path.isfile(filepath):
29
raise FileNotFoundException(f"{filepath} does not exist")
30
31
32
def parse_args():
33
# Initialize variables for file paths and verbose mode
34
input_filepath = None
35
verbose_mode = False
36
passwords_filepath = None
37
38
# Parse command-line arguments
39
args = sys.argv[1:]
40
41
while args:
42
arg = args.pop(0)
43
if arg in ("-f", "--file"):
44
# Check if there are more arguments after the flag
45
if not args:
46
print("Error: Missing input file path.")
47
raise MissingArgumentException
48
input_filepath = args.pop(0)
49
check_file_exists(input_filepath)
50
elif arg in ("-v", "--verbose"):
51
verbose_mode = logging.DEBUG
52
elif arg in ("-w", "--words"):
53
# Check if there are more arguments after the flag
54
if not args:
55
print("Error: Missing passwords file path.")
56
raise MissingArgumentException
57
passwords_filepath = args.pop(0)
58
check_file_exists(passwords_filepath)
59
else:
60
raise UnkownFlagException
61
62
return Args(input_filepath, verbose_mode, passwords_filepath)
63
64
65
def main(protected_zip_path, wordlist_path):
66
with zipfile.ZipFile(protected_zip_path) as z:
67
with open(wordlist_path) as wordlist_file:
68
for password_line in wordlist_file:
69
password = password_line.strip()
70
try:
71
z.extractall(pwd=password.encode("utf-8"))
72
logging.info(f"password found: {password}")
73
break
74
except zipfile.BadZipFile as e:
75
logging.error(f"the zip file is invalid - {e}")
76
raise e
77
except RuntimeError as e:
78
logging.debug(f"bad password: {password}")
79
80
81
if __name__ == "__main__":
82
args = parse_args()
83
configure_logging(args.verbose_mode)
84
main(args.input_filepath, args.passwords_filepath)
85
86