ActiveState Powered by ActiveState

Recipe 59873: Random Password Generation


This is a code snippet to generate an 8 character alphanumeric password.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from whrandom import choice
import string

def GenPasswd():
    chars = string.letters + string.digits
    for i in range(8):
        newpasswd = newpasswd + choice(chars)
    return newpasswd

def GenPasswd2(length=8, chars=string.letters + string.digits):
    return ''.join([choice(chars) for i in range(length)])

Discussion

Useful when you're creating new user accounts and want to assign them a random password.

The GenPasswd2 version allows one to specify the length of the password and the character sets to use to choose from, and shows off how to use list comprehensions to eliminate for loops.

>>> GenPasswd2()
'Bq1RVx1y'
>>> GenPasswd2(12)
'HpRGxrmzpg4V'
>>> GenPasswd2(12, string.letters)
'wIfJWRjYWCYu'

Comments

  1. 1. At 8:20 a.m. on 8 oct 2001, Diana McC said:

    How do you use it? I am interested in your snippet of code. But as I an an extream newbe I need a little hand holding to get it going. And suggestions? Thatnks Diana. diana_org@hotmail.com

  2. 2. At 12:35 p.m. on 14 oct 2001, Alex Martelli said:

    it's easy to use this module. save it as a textfile, say makepass.py in some directory on your sys.path, then from any Python script, or interactively (in the Python interpreter, IDLE, etc):

    import makepass
    print makepass.GenPasswd2()
    

    and similar uses. Write help@python.org for any more help request!

  3. 3. At 4:57 p.m. on 4 jan 2005, Juan Stang said:

    Bug. Fun little snippet, comes in handy, but there's a little bug, of course ;)

    The var 'newpasswd' is being created inside the 'for', and so may not be returned. The correct snippet should be:

    def GenPasswd():
        chars = string.letters + string.digits
        newpasswd = ''
        for i in range(8):
            newpasswd = newpasswd + choice(chars)
        return newpasswd
    

    That should do it ...

  4. 4. At 1:33 p.m. on 14 oct 2006, Rudolph Froger said:

    Even shorter. How about:

    return ''.join([choice(chars) for i in xrange(8)])
    
  5. 5. At 5:42 a.m. on 25 oct 2007, Bartosz Ptaszynski said:

    Easier way :). Hey this is an easier way:

    <pre lang="python"> import string from random import Random

    newpasswd = ''.join( Random().sample(string.letters+string.digits, 12) ) </pre>

    Cheers

Sign in to comment