How to Make a Password Generator in Python

Learn how to make a password generator in Python with the ability to choose the length of each character type using the built-in random, string and argparse modules.
  · · 8 min read · Updated aug 2022 · Ethical Hacking

Password generators are tools that allow the user to create random and customized strong passwords based on preferences.

In this tutorial, we will make a command-line tool in Python for generating passwords. We will use the argparse module to make it easier to parse the command line arguments the user has provided. Let us get started.


Let us import some modules. For this program, we just need the ArgumentParser class from argparse and the random and secrets modules. We also get the string module which just has some collections of letters and numbers. We don't have to install any of these because they come with Python:

from argparse import ArgumentParser
import secrets
import random
import string

If you're not sure how the random and secrets modules works. Check this tutorial that covers generating random data with these modules.

Get: Build 24 Ethical Hacking Scripts & Tools with Python Book

Setting up the Argument Parser

Now we continue with setting up the argument parser. To do this, we create a new instance of the ArgumentParser class to our parser variable. We give the parser a name and a description. This information will appear if the user provides the -h argument when running our program, it will also tell them the available arguments:

# Setting up the Argument Parser
parser = ArgumentParser(
    prog='Password Generator.',
    description='Generate any number of passwords with this tool.'

We continue by adding arguments to the parser. The first four will be the number of each character type; numbers, lowercase, uppercase, and special characters, we also set the type of these arguments as int:

# Adding the arguments to the parser
parser.add_argument("-n", "--numbers", default=0, help="Number of digits in the PW", type=int)
parser.add_argument("-l", "--lowercase", default=0, help="Number of lowercase chars in the PW", type=int)
parser.add_argument("-u", "--uppercase", default=0, help="Number of uppercase chars in the PW", type=int)
parser.add_argument("-s", "--special-chars", default=0, help="Number of special chars in the PW", type=int)

Next, if the user wants to instead pass the total number of characters of the password, and doesn't want to specify the exact number of each character type, then the -t or --total-length argument handles that:

# add total pw length argument
parser.add_argument("-t", "--total-length", type=int, 
                    help="The total password length. If passed, it will ignore -n, -l, -u and -s, " \
                    "and generate completely random passwords with the specified length")

The next two arguments are the output file where we store the passwords, and the number of passwords to generate. The amount will be an integer and the output file is a string (default):

# The amount is a number so we check it to be of type int.
parser.add_argument("-a", "--amount", default=1, type=int)
parser.add_argument("-o", "--output-file")

Last but not least, we parse the command line for these arguments with the parse_args() method of the ArgumentParser class. If we don't call this method the parser won't check for anything and won't raise any exceptions:

# Parsing the command line arguments.
args = parser.parse_args()

The Password Loop

We continue with the main part of the program: the password loop. Here we generate the number of passwords specified by the user.

We need to define the passwords list that will hold all the generated passwords:

# list of passwords
passwords = []
# Looping through the amount of passwords.
for _ in range(args.amount):

In the for loop, we first check whether total_length is passed. If so, then we directly generate the random password using the length specified:

    if args.total_length:
        # generate random password with the length
        # of total_length based on all available characters
            [secrets.choice(string.digits + string.ascii_letters + string.punctuation) \
                for _ in range(args.total_length)]))

We use the secrets module instead of the random so we can generate cryptographically strong random passwords, more in this tutorial.

Otherwise, we make a password list that will first hold all the possible letters and then the password string:

        password = []

Now we add the possible letters, numbers, and special characters to the password list. For each of the types, we check if it's passed to the parser. We get the respective letters from the string module:

        # If / how many numbers the password should contain  
        for _ in range(args.numbers):

        # If / how many uppercase characters the password should contain   
        for _ in range(args.uppercase):
        # If / how many lowercase characters the password should contain   
        for _ in range(args.lowercase):

        # If / how many special characters the password should contain   
        for _ in range(args.special_chars):

Then we use the random.shuffle() function to mix up the list. This is done in place:

        # Shuffle the list with all the possible letters, numbers and symbols.

After this, we join the resulting characters with an empty string "" so we have the string version of it:

        # Get the letters of the string up to the length argument and then join them.
        password = ''.join(password)

Last but not least, we append this password to the passwords list.

        # append this password to the overall list of password.

Again, if you're not sure how the random module works, check this tutorial that covers generating random data with this module.

Saving the Passwords

After the password loop, we check if the user specified the output file. If that is the case, we simply open the file (which will be made if it doesn't exist) and write the list of passwords:

# Store the password to a .txt file.
if args.output_file:
    with open(args.output_file, 'w') as f:

In all cases, we print out the passwords.


Related: Build 24 Ethical Hacking Scripts & Tools with Python Book


Now let's use the script for generating different password combinations. First, let's print the help:

$ python --help
usage: Password Generator. [-h] [-n NUMBERS] [-l LOWERCASE] [-u UPPERCASE] [-s SPECIAL_CHARS] [-t TOTAL_LENGTH]
                           [-a AMOUNT] [-o OUTPUT_FILE]

Generate any number of passwords with this tool.

optional arguments:
  -h, --help            show this help message and exit
  -n NUMBERS, --numbers NUMBERS
                        Number of digits in the PW
  -l LOWERCASE, --lowercase LOWERCASE
                        Number of lowercase chars in the PW
  -u UPPERCASE, --uppercase UPPERCASE
                        Number of uppercase chars in the PW
  -s SPECIAL_CHARS, --special-chars SPECIAL_CHARS
                        Number of special chars in the PW
  -t TOTAL_LENGTH, --total-length TOTAL_LENGTH
                        The total password length. If passed, it will ignore -n, -l, -u and -s, and generate completely   
                        random passwords with the specified length
  -a AMOUNT, --amount AMOUNT
  -o OUTPUT_FILE, --output-file OUTPUT_FILE

A lot to cover, starting with the --total-length or -t parameter:

$ python --total-length 12

This generated a password with a length of 12 and contains all the possible characters. Okay, let's generate 10 different passwords like that:

$ python --total-length 12 --amount 10

Awesome! Let's generate a password with 5 lowercase characters, 2 uppercase, 3 digits, and one special character, a total of 11 characters:

$ python -l 5 -u 2 -n 3 -s 1

Okay, generating 5 different passwords based on the same rule:

$ python -l 5 -u 2 -n 3 -s 1 -a 5

That's great! We can also generate random pins of 6 digits:

$ python -n 6 -a 5 

Adding 4 uppercase characters and saving to a file named keys.txt:

$ python -n 6 -u 4 -a 5 --output-file keys.txt

A new keys.txt file will appear in the current working directory that contains these passwords, you can generate as many passwords as you can:

$ python -n 6 -u 4 -a 5000 --output-file keys.txt


Excellent! You have successfully created a password generator using Python code! See how you can add more features to this program!

For long lists, you may want to not print the results into the console, so you can omit the last line of the code that prints the generated passwords to the console.

Get the complete code here.

Finally, we have an Ethical Hacking with Python Ebook, where we build 24 hacking tools and scripts from scratch using Python! Make sure to check it out if you're interested.

Learn also: How to Extract Saved WiFi Passwords in Python.

Happy coding ♥

View Full Code
Sharing is caring!

Read Also

Comment panel