Recipe 10.1. Generating Random Passwords
Credit: Devin Leung
Problem
You
need to create new passwords randomlyfor example, to assign
them automatically to new user accounts.
Solution
One of the chores of system administration is installing new user
accounts. Assigning a different, totally random password to each new
user is a good idea. Save the following code as
makepass.py:
from random import choice
import string
def GenPasswd(length=8, chars=string.letters+string.digits):
return ''.join([ choice(chars) for i in range(length) ])
Discussion
This recipe is useful when you are creating new user accounts and
assigning each of them a different, totally random password. For
example, you can print six passwords of length 12:
>>> import makepassOf course, such totally random passwords, while providing an
>>> for i in range(6):
... print makepass.GenPasswd(12)
...
uiZWGSJLWjOI
FVrychdGsAaT
CGCXZAFGjsYI
TPpQwpWjQEIi
HMBwIvRMoIvh
excellent theoretical basis for security, are impossibly hard to
remember for most users. If you require users to stick with their
assigned passwords, many users will probably write them down. The
best you can hope for is that new users will set their own passwords
at their first login, assuming, of course, that the system
you're administering lets each user change his own
password. (Most operating systems do, but you might be assigning
passwords for other kinds of services that unfortunately often lack
such facilities.)A password that is written down anywhere is a serious security risk:
pieces of paper get lost, misplaced, and peeked at. From a pragmatic
point of view, you might be better off assigning passwords that are
not totally random; users are more likely to remember them and less
likely to write them down (see Recipe 10.2). This practice may violate
the theory of password security, but, as all practicing system
administrators know, pragmatism trumps theory.
See Also
Recipe 10.2; documentation
of the standard library module random in the
Library Reference and Python in a
Nutshell.