Python Snippets

Secure Password Generator with Customizable Rules

import secrets
import string
import argparse

def generate_password(length=12, upper=True, digits=True, special=True):
    """Generate a secure random password with customizable complexity rules."""
    chars = string.ascii_lowercase
    if upper:
        chars += string.ascii_uppercase
    if digits:
        chars += string.digits
    if special:
        chars += string.punctuation
    
    while True:
        password = ''.join(secrets.choice(chars) for _ in range(length))
        # Ensure password meets all complexity requirements
        if (not upper or any(c.isupper() for c in password)) and \
           (not digits or any(c.isdigit() for c in password)) and \
           (not special or any(c in string.punctuation for c in password)):
            return password

def main():
    parser = argparse.ArgumentParser(description='Generate secure random passwords.')
    parser.add_argument('-l', '--length', type=int, default=12, help='Password length')
    parser.add_argument('--no-upper', action='store_false', help='Exclude uppercase letters')
    parser.add_argument('--no-digits', action='store_false', help='Exclude digits')
    parser.add_argument('--no-special', action='store_false', help='Exclude special characters')
    parser.add_argument('-n', '--count', type=int, default=1, help='Number of passwords to generate')
    
    args = parser.parse_args()
    
    for _ in range(args.count):
        print(generate_password(
            length=args.length,
            upper=not args.no_upper,
            digits=not args.no_digits,
            special=not args.no_special
        ))

if __name__ == '__main__':
    main()

Explanation

This Python script generates secure, random passwords with customizable complexity rules. Here’s why it’s useful:

  1. Security: Uses Python’s secrets module (cryptographically secure random generator) instead of the standard random module
  2. Customizability: Allows control over password length and character sets (uppercase, digits, special characters)
  3. Guaranteed Complexity: Ensures the generated password contains at least one character from each required character set
  4. CLI Interface: Provides a convenient command-line interface for easy integration into workflows

Features

How to Run

  1. Save the code to a file (e.g., password_generator.py)
  2. Run from command line with various options:
    • Basic usage: python password_generator.py
    • Generate 5 passwords of length 16: python password_generator.py -l 16 -n 5
    • Generate password without special characters: python password_generator.py --no-special
    • Minimal password (only lowercase): python password_generator.py --no-upper --no-digits --no-special

This tool is particularly useful for system administrators, developers, and anyone who needs to create secure credentials while maintaining control over password complexity requirements.