makepasswd

Edward S. Vinyard vinyard at jpl.nasa.gov
Mon Jun 4 14:55:41 EDT 2001


On Mon, 4 Jun 2001, Peter I. Hansen wrote:
> Hi,
>
> Is there a python funtion to generate passwords ? (Like the perl
> makepasswd)
>
> /Peter

I use the following script to do the job.  It might be a good place to
start.  (If you discover a better way, or make improvements, I'd like to
hear about it/them.)

Cheers,
Ed Vinyard

--- choose_password.py ---
#!/usr/bin/env python
default_length = 6

help_message = __doc__ = """
choose_password.py
Author: Edward S. Vinyard (Edward.S.Vinyard at jpl.nasa.gov)

Choose a good random password containing uppercase letters, lowercase
letters, numbers, and punctuation.  Other composition can be acheived
with the '-from' argument.

usage: choose_password.py [-from [l][u][d][p]] [password-length]

       -from           specifies the characters that will be used; must be
                       followed by one or more of the following modifiers.
		       If unspecified, the program will assume '-from lupd'.
           l           lower case letters (a-z)
           u           upper case letters (A-Z)
           d           digits (0-9)
           p           punctuation (!@#$%...)

       password-length  is a positive integer.

Example: "choose_password.py -from dp 8" would generate a password 8
         characters in length composed of only digit and punctuation
         characters.
"""
import sys
## PORTABILITY: This section will bind the names we need to run, based
## on their availability in the run environment.
if 'executable' in dir(sys):		# KLUDGE: JPython/CPython detection
    from whrandom import random		# in [0.0, 1.0)
    from string import lowercase, uppercase, digits, punctuation
else:
    import java.lang.Math
    random = java.lang.Math.random	# in [0.0, 1.0)
    lowercase = "abcdefghijklmnopqrstuvwxyz"
    uppercase = "ABCDEFGHIJKLMNOPQSTUVWXYZ"
    digits = "0123456789"
    punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

##----------------------------------------------------------------------
def choose_character():
    """choose_character() -> character

    Choose a password string character from uppercase letters,
    lowercase letters, digits, and punctuation."""

    ## PORTABILITY: This could be written more elegantly using
    ## whrandom.choice(), but for portability to jpython, this method
    ## is better.
    index = int(random() * len(password_chars))

    return password_chars[index]

##----------------------------------------------------------------------
def choose_password(length):
    """choose_password(length=6) -> string

    Choose a password containing 'length' characters."""

    password = ""

    for x in range(length):
	password = password + choose_character()

    return password

##----------------------------------------------------------------------
def parse_char_spec(char_spec):
    """parse_char_spec(char_spec) -> string

    Parse the argument to the '-from' command line argument."""

    password_chars = ""

    for c in char_spec:
	try:
	    password_chars = password_chars + {'l' : lowercase,
					       'u' : uppercase,
					       'd' : digits,
					       'p' : punctuation}[c]
	except KeyError:
	    print "ERROR: Unrecognized character specification '%s'" % c

    if password_chars == '':
        print "ERROR: Empty character specification.  Assuming 'ludp'."
        return parse_char_spec("ludp")
    else:
        return password_chars

##----------------------------------------------------------------------
def parse_args(args):
    """parse_args(arguments) -> (length, password_chars)

    Parse the command line arguments."""

    if '-help' in args:
	print help_message
	sys.exit(0)

    if '-from' in args:			# Determine password characters
	only_index = args.index('-from')
	char_spec = args[only_index + 1]
	args.remove('-from')
	args.remove(char_spec)
	password_chars = parse_char_spec(char_spec)
    else:
	print ("WARNING: Password composition unspecified.  " +
	       "Assuming '-from ludp' argument.")
	password_chars = lowercase + uppercase + digits + punctuation

    if len(args) < 2:			# Determine password length
        print ("WARNING: Password length unspecified.  " +
               "Assuming password of length 6.")
        length = default_length
    elif int(args[1]) < 1:
        print ("ERROR: Password length must be a positive integer.  " +
               "Assuming password of length 6.")
        length = default_length
    else:
        length = int(args[1])

    return (length, password_chars)

##----------------------------------------------------------------------
if __name__ == "__main__":
    (length, password_chars) = parse_args(sys.argv)
    length = int(sys.argv[1])
    print ("Generating %d character password from\n%s\n..." %
	   (length, password_chars))
    print "Password %s is 1 in %d^%d" % (choose_password(length),
					 len(password_chars),
					 length)




More information about the Python-list mailing list