|
| 1 | +#!/usr/bin/python3 |
| 2 | + |
| 3 | +import random |
| 4 | +import string |
| 5 | +import secrets |
| 6 | +import argparse |
| 7 | +from typing import List, Dict |
| 8 | + |
| 9 | + |
| 10 | +class PasswordGenerator: |
| 11 | + def __init__(self): |
| 12 | + self.character_sets = { |
| 13 | + 'lowercase': string.ascii_lowercase, |
| 14 | + 'uppercase': string.ascii_uppercase, |
| 15 | + 'digits': string.digits, |
| 16 | + 'symbols': string.punctuation |
| 17 | + } |
| 18 | + |
| 19 | + def generate_password(self, length: int = 12, **requirements) -> str: |
| 20 | + """ |
| 21 | + Generate a password with specified requirements |
| 22 | + |
| 23 | + Args: |
| 24 | + length: Length of the password |
| 25 | + requirements: Boolean flags for character types |
| 26 | + - lowercase: Include lowercase letters |
| 27 | + - uppercase: Include uppercase letters |
| 28 | + - digits: Include digits |
| 29 | + - symbols: Include symbols |
| 30 | + |
| 31 | + Returns: |
| 32 | + Generated password string |
| 33 | + """ |
| 34 | + # Default requirements if none specified |
| 35 | + if not any(requirements.values()): |
| 36 | + requirements = { |
| 37 | + 'lowercase': True, |
| 38 | + 'uppercase': True, |
| 39 | + 'digits': True, |
| 40 | + 'symbols': True |
| 41 | + } |
| 42 | + |
| 43 | + # Build character pool based on requirements |
| 44 | + character_pool = "" |
| 45 | + required_chars = [] |
| 46 | + |
| 47 | + for char_type, include in requirements.items(): |
| 48 | + if include and char_type in self.character_sets: |
| 49 | + chars = self.character_sets[char_type] |
| 50 | + character_pool += chars |
| 51 | + # Add at least one character from each required type |
| 52 | + required_chars.append(secrets.choice(chars)) |
| 53 | + |
| 54 | + if not character_pool: |
| 55 | + raise ValueError("At least one character type must be selected") |
| 56 | + |
| 57 | + # Calculate remaining characters needed |
| 58 | + remaining_length = length - len(required_chars) |
| 59 | + if remaining_length < 0: |
| 60 | + raise ValueError(f"Password length too short for required character types. Minimum: {len(required_chars)}") |
| 61 | + |
| 62 | + # Generate remaining characters |
| 63 | + additional_chars = [secrets.choice(character_pool) for _ in range(remaining_length)] |
| 64 | + |
| 65 | + # Combine and shuffle |
| 66 | + all_chars = required_chars + additional_chars |
| 67 | + secrets.SystemRandom().shuffle(all_chars) |
| 68 | + |
| 69 | + return ''.join(all_chars) |
| 70 | + |
| 71 | + def generate_multiple_passwords(self, count: int = 5, **kwargs) -> List[str]: |
| 72 | + """Generate multiple passwords with the same settings""" |
| 73 | + return [self.generate_password(**kwargs) for _ in range(count)] |
| 74 | + |
| 75 | + def check_password_strength(self, password: str) -> Dict[str, bool]: |
| 76 | + """Check the strength of a password""" |
| 77 | + return { |
| 78 | + 'has_lowercase': any(c.islower() for c in password), |
| 79 | + 'has_uppercase': any(c.isupper() for c in password), |
| 80 | + 'has_digit': any(c.isdigit() for c in password), |
| 81 | + 'has_symbol': any(c in string.punctuation for c in password), |
| 82 | + 'min_length': len(password) >= 8, |
| 83 | + 'good_length': len(password) >= 12 |
| 84 | + } |
| 85 | + |
| 86 | + |
| 87 | +def get_user_preferences(): |
| 88 | + """Get password generation preferences from user input""" |
| 89 | + print("=== Password Generator ===") |
| 90 | + |
| 91 | + # Get password length |
| 92 | + while True: |
| 93 | + try: |
| 94 | + length = int(input("Enter password length (default 12): ") or "12") |
| 95 | + if length < 4: |
| 96 | + print("Password length must be at least 4 characters.") |
| 97 | + continue |
| 98 | + break |
| 99 | + except ValueError: |
| 100 | + print("Please enter a valid number.") |
| 101 | + |
| 102 | + # Get character type preferences |
| 103 | + print("\nSelect character types to include:") |
| 104 | + requirements = { |
| 105 | + 'lowercase': input("Include lowercase letters? (y/n, default y): ").lower() != 'n', |
| 106 | + 'uppercase': input("Include uppercase letters? (y/n, default y): ").lower() != 'n', |
| 107 | + 'digits': input("Include digits? (y/n, default y): ").lower() != 'n', |
| 108 | + 'symbols': input("Include symbols? (y/n, default y): ").lower() != 'n' |
| 109 | + } |
| 110 | + |
| 111 | + # Get number of passwords to generate |
| 112 | + while True: |
| 113 | + try: |
| 114 | + count = int(input("\nHow many passwords to generate? (default 1): ") or "1") |
| 115 | + if count < 1: |
| 116 | + print("Please enter at least 1.") |
| 117 | + continue |
| 118 | + break |
| 119 | + except ValueError: |
| 120 | + print("Please enter a valid number.") |
| 121 | + |
| 122 | + return length, requirements, count |
| 123 | + |
| 124 | + |
| 125 | +def display_password_strength(password: str, generator: PasswordGenerator): |
| 126 | + """Display strength analysis for a password""" |
| 127 | + strength = generator.check_password_strength(password) |
| 128 | + |
| 129 | + print(f"\nPassword: {password}") |
| 130 | + print("Strength Analysis:") |
| 131 | + print(f"Length: {len(password)} characters") |
| 132 | + print(f"Lowercase letters: {'Yes' if strength['has_lowercase'] else 'No'}") |
| 133 | + print(f"Uppercase letters: {'Yes' if strength['has_uppercase'] else 'No'}") |
| 134 | + print(f"Digits: {'Yes' if strength['has_digit'] else 'No'}") |
| 135 | + print(f"Symbols: {'Yes' if strength['has_symbol'] else 'No'}") |
| 136 | + |
| 137 | + # Overall strength rating |
| 138 | + criteria_met = sum(strength.values()) |
| 139 | + if criteria_met >= 6: |
| 140 | + rating = "Strong" |
| 141 | + elif criteria_met >= 4: |
| 142 | + rating = "Good" |
| 143 | + else: |
| 144 | + rating = "Weak" |
| 145 | + |
| 146 | + print(f"Overall Rating: {rating}") |
| 147 | + |
| 148 | + |
| 149 | +def main(): |
| 150 | + """Main function with command line interface""" |
| 151 | + parser = argparse.ArgumentParser(description='Generate secure passwords') |
| 152 | + parser.add_argument('-l', '--length', type=int, default=12, help='Password length') |
| 153 | + parser.add_argument('-n', '--number', type=int, default=1, help='Number of passwords') |
| 154 | + parser.add_argument('--no-lower', action='store_true', help='Exclude lowercase letters') |
| 155 | + parser.add_argument('--no-upper', action='store_true', help='Exclude uppercase letters') |
| 156 | + parser.add_argument('--no-digits', action='store_true', help='Exclude digits') |
| 157 | + parser.add_argument('--no-symbols', action='store_true', help='Exclude symbols') |
| 158 | + parser.add_argument('--interactive', action='store_true', help='Use interactive mode') |
| 159 | + |
| 160 | + args = parser.parse_args() |
| 161 | + |
| 162 | + generator = PasswordGenerator() |
| 163 | + |
| 164 | + if args.interactive or not any(vars(args).values()): |
| 165 | + # Interactive mode |
| 166 | + length, requirements, count = get_user_preferences() |
| 167 | + else: |
| 168 | + # Command line mode |
| 169 | + length = args.length |
| 170 | + count = args.number |
| 171 | + requirements = { |
| 172 | + 'lowercase': not args.no_lower, |
| 173 | + 'uppercase': not args.no_upper, |
| 174 | + 'digits': not args.no_digits, |
| 175 | + 'symbols': not args.no_symbols |
| 176 | + } |
| 177 | + |
| 178 | + try: |
| 179 | + # Generate passwords |
| 180 | + if count == 1: |
| 181 | + password = generator.generate_password(length=length, **requirements) |
| 182 | + display_password_strength(password, generator) |
| 183 | + else: |
| 184 | + passwords = generator.generate_multiple_passwords(count=count, length=length, **requirements) |
| 185 | + print(f"\nGenerated {count} passwords:") |
| 186 | + for i, password in enumerate(passwords, 1): |
| 187 | + print(f"{i:2d}. {password}") |
| 188 | + |
| 189 | + # Show strength for first password as example |
| 190 | + if passwords: |
| 191 | + display_password_strength(passwords[0], generator) |
| 192 | + |
| 193 | + except ValueError as e: |
| 194 | + print(f"Error: {e}") |
| 195 | + except Exception as e: |
| 196 | + print(f"Unexpected error: {e}") |
| 197 | + |
| 198 | + |
| 199 | +if __name__ == "__main__": |
| 200 | + main() |
0 commit comments