Python Snippets

Automatic Password Generator with Customizable Complexity

import random
import string
import argparse

def generate_password(length=12, include_uppercase=True, include_lowercase=True, 
                      include_digits=True, include_symbols=True, exclude_ambiguous=False):
    """
    Generate a secure random password with customizable complexity options.
    
    Args:
        length (int): Length of the password (default: 12)
        include_uppercase (bool): Include uppercase letters (default: True)
        include_lowercase (bool): Include lowercase letters (default: True)
        include_digits (bool): Include digits (default: True)
        include_symbols (bool): Include special symbols (default: True)
        exclude_ambiguous (bool): Exclude ambiguous characters like 0, O, l, 1 (default: False)
    
    Returns:
        str: Generated password
    """
    if length < 1:
        raise ValueError("Password length must be at least 1")
    
    # Define character sets
    uppercase = string.ascii_uppercase
    lowercase = string.ascii_lowercase
    digits = string.digits
    symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?"
    
    # Remove ambiguous characters if requested
    if exclude_ambiguous:
        uppercase = uppercase.replace('O', '').replace('I', '')
        lowercase = lowercase.replace('l', '').replace('o', '')
        digits = digits.replace('0', '').replace('1', '')
    
    # Build character pool based on selected options
    char_pool = ""
    required_chars = []
    
    if include_uppercase:
        char_pool += uppercase
        required_chars.append(random.choice(uppercase))
    
    if include_lowercase:
        char_pool += lowercase
        required_chars.append(random.choice(lowercase))
    
    if include_digits:
        char_pool += digits
        required_chars.append(random.choice(digits))
    
    if include_symbols:
        char_pool += symbols
        required_chars.append(random.choice(symbols))
    
    if not char_pool:
        raise ValueError("At least one character type must be selected")
    
    # Generate remaining characters
    remaining_length = length - len(required_chars)
    if remaining_length < 0:
        # If length is less than required character types, adjust
        required_chars = required_chars[:length]
        remaining_length = 0
    
    random_chars = [random.choice(char_pool) for _ in range(remaining_length)]
    
    # Combine required and random characters
    password_chars = required_chars + random_chars
    
    # Shuffle to avoid predictable patterns
    random.shuffle(password_chars)
    
    return ''.join(password_chars)

def main():
    parser = argparse.ArgumentParser(description="Generate secure random passwords")
    parser.add_argument("-l", "--length", type=int, default=12, 
                        help="Password length (default: 12)")
    parser.add_argument("-n", "--count", type=int, default=1, 
                        help="Number of passwords to generate (default: 1)")
    parser.add_argument("--no-uppercase", action="store_true", 
                        help="Exclude uppercase letters")
    parser.add_argument("--no-lowercase", action="store_true", 
                        help="Exclude lowercase letters")
    parser.add_argument("--no-digits", action="store_true", 
                        help="Exclude digits")
    parser.add_argument("--no-symbols", action="store_true", 
                        help="Exclude symbols")
    parser.add_argument("--exclude-ambiguous", action="store_true", 
                        help="Exclude ambiguous characters (0, O, l, 1)")
    
    args = parser.parse_args()
    
    try:
        for i in range(args.count):
            password = generate_password(
                length=args.length,
                include_uppercase=not args.no_uppercase,
                include_lowercase=not args.no_lowercase,
                include_digits=not args.no_digits,
                include_symbols=not args.no_symbols,
                exclude_ambiguous=args.exclude_ambiguous
            )
            print(password)
    except ValueError as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()

What This Code Does

This is a robust password generator that creates cryptographically secure random passwords with customizable complexity options. The tool allows users to specify password length, character types to include or exclude, and whether to avoid ambiguous characters that might be difficult to distinguish.

Key features:

Why It’s Useful

Strong, unique passwords are essential for online security, but creating and remembering complex passwords is challenging. This tool solves that problem by automatically generating secure passwords that meet various complexity requirements. It’s particularly useful for:

How to Run It

Save the code to a file named password_generator.py and run it from the command line:

# Generate a default 12-character password
python password_generator.py

# Generate a 20-character password
python password_generator.py --length 20

# Generate a password without symbols
python password_generator.py --no-symbols

# Generate 5 passwords with only letters and digits
python password_generator.py --count 5 --no-symbols

# Generate a password excluding ambiguous characters
python password_generator.py --exclude-ambiguous

# Get help on all options
python password_generator.py --help

The generated passwords will be printed to standard output, one per line. For security, avoid printing passwords to the terminal in production environments where others might see them.