Generate Strong Random Passwords with Custom Rules in Python
Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.
Python code
21 linesimport secrets
import string
def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
pool = ''
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_punct:
pool += string.punctuation
if not pool:
raise ValueError("At least one character set must be enabled.")
return ''.join(secrets.choice(pool) for _ in range(length))
if __name__ == "__main__":
print(generate_password())
print(generate_password(12, use_punct=False))
print(generate_password(20, use_lower=False, use_digits=False))
Output
M7@jK#l9XzQ2$rTp
bC3@kL9dF2
Q#W$E%R&T*Y^U(I)O_P
How it works
The secrets module is preferred over random for generating cryptographically secure passwords. The function builds a character pool from string constants based on the user's boolean flags, then selects characters using secrets.choice(). The check if not pool ensures at least one character set is enabled, preventing an infinite loop or empty password. By default, the function generates a 16-character password with all character types, but you can adjust length and disable any set by passing False.
Common mistakes
- Using `random` instead of `secrets`, which is not suitable for passwords because it is not cryptographically secure.
- Forgetting to check that at least one character set is enabled, leading to an empty password or error.
- Using `string.whitespace` or other characters that might cause issues in URLs or command-line environments.
Variations
- Use `os.urandom` with base64 encoding for a simpler password format without choosing character sets.
- Add a `unique_chars` parameter that ensures no duplicate characters in the password by sampling without replacement.
Real-world use cases
- Generating temporary admin passwords when provisioning cloud VMs or databases via automation scripts.
- Creating user-friendly passwords for internal tool accounts where certain special characters must be avoided.
- Automatically rotating API keys or service account secrets that require a specific mix of character types.
Sponsored
More from Automation & scripting
- Batch Rename Hundreds of Files in Python easy
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Build a Network Ping Monitor in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Create a Simple HTTP File Server in Python easy
Keep learning
Related tutorials and quizzes for this topic.