I l@ve RuBoard Previous Section Next Section

7.3 Generating Random Passwords

Credit: Devin Leung

7.3.1 Problem

You need to create new passwords randomly梖or example, to assign them automatically to new user accounts.

7.3.2 Solution

One of the chores of system administration is installing a lot of new user accounts. Assigning each new user a different, totally random password is a good idea in such cases. Save the following as makepass.py:

from random import choice
import string

# Python 1.5.2 style
def GenPasswd(length=8, chars=string.letters+string.digits):
    newpasswd = []
    for i in range(length):
    return string.join(newpasswd,'')

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

7.3.3 Discussion

This recipe is useful when creating new user accounts and assigning each of them a different, totally random password. The GenPasswd2 version shows how to use some features that are new in Python 2.0 (e.g., list comprehensions and string methods).

Here's how to print out 6 passwords (letters only, of length 12):

>>> import makepass, string
>>> for i in range(6):
...    print makepass.GenPasswd2(12, string.letters)

Of course, such totally random passwords, while providing an excellent theoretical basis for security, are impossibly hard to remember for most users. If you require users to stick with them, many users will probably write down their passwords somewhere. 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 their own password (most operating systems do, but you might be assigning passwords for other kinds of services without such facilities).

A password that is written down anywhere is a serious security risk, since pieces of paper get lost, misplaced, and peeked at. Therefore, from a pragmatic point of view, you might be better off assigning passwords that are not totally random; the users are more likely to remember these and less likely to write them down (see Recipe 7.4). This may violate the theory of password security, but, as all practicing system administrators know, pragmatism trumps theory.

7.3.4 See Also

Recipe 7.4; documentation of the standard library module random in the Library Reference.

    I l@ve RuBoard Previous Section Next Section