Path: blob/master/exercices/imperative/zip-bruteforcer/solution_argparse.py
306 views
# password = 'a' or 'xiphihumeralis'12import argparse3import logging4import os5import zipfile678def configure_logging(loglevel):9logging.basicConfig(level=loglevel)101112def file_exists(filepath):13if not os.path.isfile(filepath):14raise argparse.ArgumentTypeError(f"{filepath} does not exist")15return filepath161718def parse_args():19parser = argparse.ArgumentParser(description="zip bruteforcer")20parser.add_argument(21"-v",22"--verbose",23help="enable verbose mode",24action="store_const",25dest="loglevel",26const=logging.DEBUG,27default=logging.INFO,28)29parser.add_argument(30"-f",31"--file",32dest="protected_zip_path",33help="path of the protected zip file",34type=file_exists,35required=True,36)37parser.add_argument(38"-w ",39"--wordlist",40dest="wordlist_path",41help="path of the wordlist file",42type=file_exists,43required=True,44)45return parser.parse_args()464748def main(protected_zip_path, wordlist_path):49with zipfile.ZipFile(protected_zip_path) as z:50with open(wordlist_path) as wordlist_file:51for password_line in wordlist_file:52password = password_line.strip()53try:54z.extractall(pwd=password.encode("utf-8"))55logging.info(f"password found: {password}")56break57except zipfile.BadZipFile as e:58logging.error(f"the zip file is invalid - {e}")59raise e60except RuntimeError as e:61logging.debug(f"bad password: {password}")626364if __name__ == "__main__":65args = parse_args()66configure_logging(args.loglevel)67main(args.protected_zip_path, args.wordlist_path)686970