This is a code snippet to generate an 8 character alphanumeric password.
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)])
|
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'
Tags: sysadmin
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
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):
and similar uses. Write help@python.org for any more help request!
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:
That should do it ...
Even shorter. How about:
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
@Bartosz, random.sample does not handle repetitions. That is, each character from input sequence will appear at most once in output sequence.
Not only this is less random than original method, it also doesn't allow creating string longer than len(chars).