Generating alphanumeric passwords (Python)

A small function to generate random passwords in Python.

I use it to ensure that initials passwords are random and strong, rather than relying on hardcoded defaults

Details

  • Language: Python

Snippet

import string
import secrets

def genPasswd(length): 
    ''' Generate a random password to use for the default user 
    '''
    chars = string.ascii_lowercase + string.digits + string.ascii_uppercase + 
    "@-.,?!"

    # Strip easily confused stuff
    remove = ["0","o","l","1", "O"]
    chars = ''.join([c for c in chars if c not in remove])

    # Construct a password    
    p = []
    for _ in range(length):
        p.append(secrets.choice(chars))

    return ''.join(p)