|
|
 |
|
Title: Random Password Generation
Submitter: Devin Leung
(other recipes)
Last Updated: 2001/05/31
Version no: 1.0
Category:
System
|
|
|
Description:
This is a code snippet to generate an 8 character alphanumeric password.
Source: Text Source
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'
|
|
Add comment
|
|
Number of comments: 5
How do you use it?, Diana McC, 2001/10/08
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
Add comment
it's easy to use this module, Alex Martelli, 2001/10/14
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!
Add comment
Bug., Juan Stang, 2005/01/04
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 ...
Add comment
Even shorter, Rudolph Froger, 2006/10/14
How about:
return ''.join([choice(chars) for i in xrange(8)])
Add comment
Easier way :), Bartosz Ptaszynski, 2007/10/25
Hey this is an easier way:
import string
from random import Random
newpasswd = ''.join( Random().sample(string.letters+string.digits, 12) )
Cheers
Add comment
|
|
|
|
|
 |
|