Python Python Free

Python: Generate a Secure Random Password

Generate a strong random password with Python using the secrets module — never use random() for passwords.

12 lines · Updated Nov 26, 2026

Preview of Python: Generate a Secure Random Password
python-password-generator.py
import secrets
import string

def generate_password(length=16, use_symbols=True):
    letters = string.ascii_letters + string.digits
    if use_symbols:
        letters += "!@#$%^&*"
    return "".join(secrets.choice(letters) for _ in range(length))

if __name__ == "__main__":
    print(generate_password(16))       # e.g. k7#Qm2$xP9!vB4z
    print(generate_password(12, False))  # letters and digits only

About this snippet

Weak and reused passwords are still the most common way accounts get taken over. This snippet generates strong random passwords in Python using the secrets module — the standard library's cryptographically secure random generator — so you can create passwords for new users, API keys, database accounts or test data safely.

Why secrets and not random?

Python's random module is designed for simulations and games; its output can be predicted if an attacker sees enough values. secrets uses the operating system's secure source of randomness and is the right tool for anything security-related.

How it works

  1. It builds an alphabet of characters — lowercase, uppercase, digits and symbols.
  2. It picks each character independently with secrets.choice() up to the requested length.
  3. It can ensure the password contains at least one character of each type, which many sites require.

How long should a password be?

  • 16 or more characters for user and admin accounts.
  • 32 or more characters for machine credentials such as database passwords and API secrets.
  • Length matters more than complexity: every extra character multiplies the number of possibilities.

Customize it

  • Remove look-alike characters (O, 0, l, 1) for passwords people must type by hand.
  • Leave out symbols that cause trouble in shell commands or connection strings.
  • For URL-safe tokens, secrets.token_urlsafe(32) is a one-liner.

FAQ

Should I store generated passwords? Never store user passwords in plain text — hash them (for example with bcrypt or Argon2). Use a password manager for your own credentials.

Related: OWASP Top 10 explained · 10 Python automation projects

How to install

Save as a script or import the function into your project. The secrets module is in the standard library — no install needed. Never use random for passwords or tokens.

Share this snippet

See all
Chat with us