Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

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.

Easy Python 3.6+ Jun 27, 2026 Automation & scripting 22 views 0 copies

Python code

14 lines
Python 3.6+
import 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

stdout
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

  1. Accept command-line arguments with `argparse` to let users specify length and character sets.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.