Skip to content

How to Generate a Secure Random Password in Python

Generate strong random passwords in Python with the secrets module: character rules, custom symbols, tokens, passphrases, a CLI generator and safe storage.

Category
Python
Versions & support
About Python →
On this page

Python’s standard library can generate strong passwords without any third-party package. The right tool is the secrets module (Python 3.6 and newer), which draws from your operating system’s cryptographically secure random source. Here is the short answer:


import secrets
import string

alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(alphabet) for _ in range(16))
print(password)

This guide explains that code and builds on it: passwords that must contain every character type, URL-safe tokens, passphrases, a reusable command-line generator, and how to store passwords safely once you have them. All examples were tested on Python 3.12 and run unchanged on any Python 3.6 or newer release.

Why Use secrets Instead of random?

Many older tutorials (including an earlier version of this one) use the random module. Don’t use it for passwords. random is built on the Mersenne Twister generator, which is fast and fine for games, simulations and sampling, but it is not cryptographically secure. Someone who sees enough of its output can work out its internal state and predict the next values. The Python documentation says so directly: the random module should not be used for security purposes.

The secrets module uses os.urandom() under the hood, the same source the operating system uses for encryption keys. It gives you three main tools:

  • secrets.choice(sequence): picks one random item from a string or list.
  • secrets.token_hex(n) / secrets.token_urlsafe(n): return n random bytes as a hex or URL-safe text string.
  • secrets.SystemRandom(): a secure drop-in replacement for the random functions such as shuffle() and sample().

If you already have code that uses random.choice(), the fix is usually one word: replace random.choice with secrets.choice. For the other uses of random, see Python random functions.

1. Generate a Random Password with secrets.choice()

The string module provides ready-made character sets: string.ascii_letters (a–z and A–Z), string.digits (0–9) and string.punctuation (32 symbols such as !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~). Join them into one alphabet and pick from it once per character:

password.py:


import secrets
import string

def generate_password(length=16):
    alphabet = string.ascii_letters + string.digits + string.punctuation
    return ''.join(secrets.choice(alphabet) for _ in range(length))

print(generate_password())
print(generate_password(24))

Run it:

python3 password.py

You get a new password each time, for example:


4cU5k#B(raYt$OSW
58e,4|Q-f@xp-SP<KO[b)h00

Each character is chosen independently from 94 possible characters, so the password has exactly the length you ask for and no pattern to exploit. If a system rejects some symbols (quotes and backslashes often cause trouble in shell scripts and config files), use a shorter symbol set, as shown in method 3.

2. Require Lowercase, Uppercase, Digits and Symbols

A fully random password can, by chance, contain no digit or no symbol. Many sign-up forms reject that. The simplest fix is the approach from the official Python documentation: generate a password and try again until it meets every rule.


import secrets
import string

def generate_password(length=16):
    if length < 4:
        raise ValueError("length must be at least 4")
    alphabet = string.ascii_letters + string.digits + string.punctuation
    while True:
        password = ''.join(secrets.choice(alphabet) for _ in range(length))
        if (any(c.islower() for c in password)
                and any(c.isupper() for c in password)
                and any(c.isdigit() for c in password)
                and any(c in string.punctuation for c in password)):
            return password

print(generate_password())

Example output:


oN;SSppL#A"=}-9A

For a 16-character password almost every attempt passes, so the loop rarely runs more than once or twice. Retrying keeps every valid password equally likely, which is why the Python documentation recommends it.

3. Guarantee One Character from Each Group (Custom Symbols)

When you need a fixed number of steps (no retry loop) or a limited symbol set, pick one character from each group first, fill the rest from all groups, and then shuffle. Use secrets.SystemRandom().shuffle(), not random.shuffle(), so the shuffle is secure too:


import secrets
import string

def generate_password(length=16, symbols="!@#$%^&*-_=+"):
    pools = [string.ascii_lowercase, string.ascii_uppercase, string.digits, symbols]
    if length < len(pools):
        raise ValueError(f"length must be at least {len(pools)}")
    # One character from each pool, then fill the rest from all pools
    chars = [secrets.choice(pool) for pool in pools]
    alphabet = ''.join(pools)
    chars += [secrets.choice(alphabet) for _ in range(length - len(pools))]
    # Shuffle with a cryptographically secure generator
    secrets.SystemRandom().shuffle(chars)
    return ''.join(chars)

print(generate_password())
print(generate_password(12, symbols="!#%"))

Example output:


ML*NwX0#Adtr0P&J
IO!fX0Yh%fuY

The symbols argument lets you match a site’s rules, for example symbols="!#%" for a system that only accepts a few special characters. Without the final shuffle, the first four characters would always follow the same lowercase-uppercase-digit-symbol order, which makes the password easier to guess.

4. Generate a Token with token_urlsafe() or token_hex()

For API keys, password-reset links, session tokens and temporary passwords sent by email, you don’t need a custom alphabet. secrets has one-line functions for that:


import secrets

print(secrets.token_urlsafe(16))   # 16 random bytes, about 22 URL-safe characters
print(secrets.token_hex(16))       # 16 random bytes, 32 hex characters

Example output:


_StgPouwbq1AXK_DM8f8dQ
f649452ea1b1134ffdef8c99810b4e25

Note that the argument is the number of random bytes, not the length of the result. token_hex(16) returns 32 characters, and token_urlsafe(16) returns about 22 characters that use only letters, digits, - and _, so they are safe in URLs and file names. With no argument, both use a secure default size (32 bytes in current Python versions).

Hex tokens contain only 0–9 and a–f, so they are a poor choice for a password that someone has to type. Also avoid cutting a hex token to an odd length: secrets.token_hex(17 // 2)[:17], a pattern found in many tutorials, returns only 16 characters, not 17.

5. Generate a Memorable Passphrase

A passphrase of random words, such as timber-velvet-bridge-lantern-jungle, is easier to remember and type than a string of symbols, and it can still be very strong. The strength comes from a large word list and truly random choice. A list of a few dozen words is far too small.

Download the EFF large word list (7,776 words, file eff_large_wordlist.txt) and pick words from it with secrets.choice():


import secrets

def load_words(path):
    with open(path, encoding="utf-8") as f:
        # Each EFF line looks like "11111<TAB>abacus": keep the last field
        return [line.split()[-1] for line in f if line.strip()]

def generate_passphrase(words, count=5, sep="-"):
    return sep.join(secrets.choice(words) for _ in range(count))

words = load_words("eff_large_wordlist.txt")
print(len(words), "words loaded")
print(generate_passphrase(words))

With the full list, each word adds about 12.9 bits of entropy. Five words give about 65 bits, and six words about 78 bits. Use six or more words for a password manager’s master password or a disk encryption passphrase.

6. Build a Command-Line Password Generator

Wrap the generator in a small script with argparse so you can choose the length and the number of passwords from the terminal:

genpass.py:


import argparse
import secrets
import string

def generate_password(length, use_symbols=True):
    alphabet = string.ascii_letters + string.digits
    if use_symbols:
        alphabet += string.punctuation
    return ''.join(secrets.choice(alphabet) for _ in range(length))

def main():
    parser = argparse.ArgumentParser(description="Generate secure random passwords")
    parser.add_argument("-l", "--length", type=int, default=16, help="password length (default: 16)")
    parser.add_argument("-n", "--count", type=int, default=1, help="how many passwords (default: 1)")
    parser.add_argument("--no-symbols", action="store_true", help="letters and digits only")
    args = parser.parse_args()

    for _ in range(args.count):
        print(generate_password(args.length, not args.no_symbols))

if __name__ == "__main__":
    main()

Generate three 20-character passwords:

python3 genpass.py -l 20 -n 3

InZ{cPe&s%]%SuknjuXy
KNhqmC7C-o>O^yn|L/By
MpH5Fl?FA!J-lU^#LA-y

Or a 12-character password with letters and digits only:

python3 genpass.py --no-symbols -l 12

Run python3 genpass.py -h to see all options. If you only need a password once, you can skip the script and use a one-liner:

python3 -c "import secrets,string; print(''.join(secrets.choice(string.ascii_letters+string.digits) for _ in range(20)))"

How Long Should a Password Be?

Password strength is measured in bits of entropy: length × log2(alphabet size). Each extra character multiplies the number of possible passwords by the size of the alphabet, so length matters more than anything else.

PasswordAlphabetEntropyGood for
8 characters94 (letters, digits, symbols)~52 bitsToo weak for new passwords
12 characters94~79 bitsMinimum for website accounts
16 characters94~105 bitsRecommended default
20 characters94~131 bitsAdmin, database and service accounts
token_hex(16)16 (hex)128 bitsAPI keys and tokens
5 EFF words7,776 words~65 bitsMemorable everyday passphrase

You can calculate it in Python:


import math

def entropy_bits(length, alphabet_size):
    return length * math.log2(alphabet_size)

print(round(entropy_bits(16, 94)))   # 105

These figures are only true for passwords chosen at random, as in the examples above. A password a person makes up, like Summer2026!, has far less real entropy than its length suggests.

Storing Passwords Safely

Generating a strong password is only half the job. If your application stores user passwords, never save them as plain text, and don’t use a fast hash such as MD5 or SHA-256 on its own. Use a slow, salted password hash. Python’s standard library includes hashlib.scrypt():


import hashlib
import hmac
import secrets

def hash_password(password):
    salt = secrets.token_bytes(16)
    key = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1)
    return salt, key

def verify_password(password, salt, key):
    new_key = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1)
    return hmac.compare_digest(new_key, key)

salt, key = hash_password("S3cure!Pass")
print(verify_password("S3cure!Pass", salt, key))   # True
print(verify_password("wrong-pass", salt, key))    # False

Store the salt next to the hash (it doesn’t need to be secret), and compare with hmac.compare_digest() to avoid timing attacks. For production web applications, the argon2-cffi or bcrypt packages, or the password hashers built into Django and similar frameworks, are good choices too. Install third-party packages inside a Python virtual environment.

Best Practices

  • Always use secrets (or secrets.SystemRandom()) for passwords, tokens and keys. Keep random for non-security work.
  • Prefer length over complexity rules. 16 random characters is a good default; use 20 or more for admin and service accounts.
  • Don’t log or print generated passwords in production code. Show them once, or write them straight to a secrets manager.
  • Use a unique password for every account and keep them in a password manager.
  • Limit the symbol set only when a system requires it, and make up for it with extra length.
  • Hash stored passwords with scrypt, Argon2 or bcrypt, never with plain MD5 or SHA-256.

FAQ

What is the best way to generate a random password in Python?

Use the secrets module: ''.join(secrets.choice(alphabet) for _ in range(16)), where alphabet is built from string.ascii_letters, string.digits and string.punctuation. It is part of the standard library, so there is nothing to install.

Is Python’s random module safe for passwords?

No. random uses a predictable pseudo-random generator (Mersenne Twister) that is designed for modelling and simulation, not security. Use secrets instead.

What is the difference between secrets.token_hex() and secrets.token_urlsafe()?

Both return random bytes as text. token_hex(n) returns 2 × n hexadecimal characters (0–9, a–f). token_urlsafe(n) uses Base64 URL-safe characters, so it is shorter for the same strength (about 1.3 characters per byte) and safe to put in a URL.

How do I make sure a password contains a digit and a symbol?

Either generate passwords in a loop until one passes all your checks (method 2), or pick one character from each required group, fill the rest at random and shuffle with secrets.SystemRandom().shuffle() (method 3).

How do I generate a random password without special characters?

Leave string.punctuation out of the alphabet: alphabet = string.ascii_letters + string.digits. Add two or three extra characters to keep the same strength. If you need a random string for something other than a password, see how to generate a random string in Python.

Which Python version do I need for the secrets module?

Python 3.6 or newer. On older versions, use random.SystemRandom(), which also reads from os.urandom().

Conclusion

To generate a random password in Python, use secrets.choice() with an alphabet from the string module, and choose a length of at least 16 characters. Add a retry loop or the pick-one-from-each-group method when a password must contain every character type, use token_urlsafe() for tokens and reset links, and use a large word list for memorable passphrases. Avoid the random module for anything security-related, and hash stored passwords with scrypt, Argon2 or bcrypt.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top