Wednesday, August 8, 2012

Password Generator In Python

Here is my small code fragment to generate random alphanumeric password for given length.

def generate_random_password(length=10):
        """
        This function will generate the random alphanumeric password of given  length.
        param length: The requied password length.

        rtype: a string containing the generated password.
        """
        letters = string.letters
        digits = string.digits
        message = letters + digits
        passwd = ''
        for i in range(length):
            passwd += random.choice(message)
        return passwd


You can call above function with the following arguments:
generate_random_password()
generate_random_password(5)
generate_random_password(length=15)

The above function can be enhanced by adding special character support etc.

Have fun :)

No comments:

Post a Comment