Path: blob/master/exercices/imperative/zip-bruteforcer/solution_sysargv.py
306 views
import logging1import os2import sys3import zipfile4from collections import namedtuple567class UnkownFlagException(Exception):8pass91011class MissingArgumentException(Exception):12pass131415class FileNotFoundException(Exception):16pass171819Args = namedtuple("Args", ["input_filepath", "verbose_mode", "passwords_filepath"])202122def configure_logging(loglevel=logging.INFO):23logging.basicConfig(level=loglevel)242526def check_file_exists(filepath):27if not os.path.isfile(filepath):28raise FileNotFoundException(f"{filepath} does not exist")293031def parse_args():32# Initialize variables for file paths and verbose mode33input_filepath = None34verbose_mode = False35passwords_filepath = None3637# Parse command-line arguments38args = sys.argv[1:]3940while args:41arg = args.pop(0)42if arg in ("-f", "--file"):43# Check if there are more arguments after the flag44if not args:45print("Error: Missing input file path.")46raise MissingArgumentException47input_filepath = args.pop(0)48check_file_exists(input_filepath)49elif arg in ("-v", "--verbose"):50verbose_mode = logging.DEBUG51elif arg in ("-w", "--words"):52# Check if there are more arguments after the flag53if not args:54print("Error: Missing passwords file path.")55raise MissingArgumentException56passwords_filepath = args.pop(0)57check_file_exists(passwords_filepath)58else:59raise UnkownFlagException6061return Args(input_filepath, verbose_mode, passwords_filepath)626364def main(protected_zip_path, wordlist_path):65with zipfile.ZipFile(protected_zip_path) as z:66with open(wordlist_path) as wordlist_file:67for password_line in wordlist_file:68password = password_line.strip()69try:70z.extractall(pwd=password.encode("utf-8"))71logging.info(f"password found: {password}")72break73except zipfile.BadZipFile as e:74logging.error(f"the zip file is invalid - {e}")75raise e76except RuntimeError as e:77logging.debug(f"bad password: {password}")787980if __name__ == "__main__":81args = parse_args()82configure_logging(args.verbose_mode)83main(args.input_filepath, args.passwords_filepath)848586