Build a Command-Line Password Generator in Python
Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.
Python code
14 linesimport secrets
import string
def generate_password(length=16):
"""Generate a cryptographically strong random password."""
alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(alphabet) for _ in range(length))
return password
if __name__ == "__main__":
# Generate and print passwords of various lengths
print("Password (default 16 chars):", generate_password())
print("Password (12 chars):", generate_password(12))
print("Password (20 chars):", generate_password(20))
Output
Password (default 16 chars): aB3$9kLmNpQrStUv
Password (12 chars): Xy7@wZ2#cFgH
Password (20 chars): JkL9*MnOpQrStUvWxYz1
How it works
The secrets module provides cryptographically secure random numbers, ideal for passwords and tokens. string.ascii_letters, string.digits, and string.punctuation combine to give a full character set. The code avoids random (which is not secure) and uses secrets.choice for each character in the loop. The if __name__ == '__main__' guard allows the function to be imported without side effects.
Common mistakes
- Using `random.choice` instead of `secrets.choice`, which is not cryptographically secure.
- Forgetting to include `string.punctuation`, making passwords weaker.
- Hardcoding length in the function instead of making it a parameter.
- Not wrapping the script in `if __name__ == '__main__'` so it runs on import.
Variations
- Accept command-line arguments with `argparse` to let users specify length and character sets.
- Exclude ambiguous characters like '0', 'O', 'l', 'I' to improve readability.
Real-world use cases
- Automating password generation for new user accounts in a DevOps deployment script.
- Generating one-time tokens or temporary credentials in a security automation pipeline.
- Creating strong passwords for application secrets during local development setup.
Sponsored
More from Automation & scripting
- Batch Rename Hundreds of Files 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
- Detect and Remove Blurry Images in Python with OpenCV medium
Keep learning
Related tutorials and quizzes for this topic.