ActiveState Code

Recipe 126629: Bare Bones Password Generator


A password generator that will generate random length alpha-numeric passwords given a range to work with.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import string
import whrandom

def generatePassword(minlen=5, maxlen=10):
 chars = string.letters + string.digits
 passwd = ""
 
 # determine password size (randomly, but between the given range)
 passwd_size = whrandom.randint(minlen, maxlen)

 for x in range(passwd_size):
  # choose a random alpha-numeric character
  passwd += whrandom.choice(chars)

 return passwd

print generatePassword()

Discussion

Password generation is useful in many cases. The only way I could imagine improving this is by somehow ensuring that the password generated is secure. This would involve checking to make sure the password contains both letters and numbers and that it contains both upper case and lower case letters. That would be nice, but its not important for most situations.

Sign in to comment