Ready to take Python coding to a new level? Explore our Python Code Generator. The perfect tool to get your code up and running in no time. Start now!
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.
Related: How to Use the Argparse Module in Python.
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 35+ Ethical Hacking Scripts & Tools with Python Book
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()
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
passwords.append("".join(
[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:
else:
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):
password.append(secrets.choice(string.digits))
# If / how many uppercase characters the password should contain
for _ in range(args.uppercase):
password.append(secrets.choice(string.ascii_uppercase))
# If / how many lowercase characters the password should contain
for _ in range(args.lowercase):
password.append(secrets.choice(string.ascii_lowercase))
# If / how many special characters the password should contain
for _ in range(args.special_chars):
password.append(secrets.choice(string.punctuation))
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.
random.shuffle(password)
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.
passwords.append(password)
Again, if you're not sure how the random module works, check this tutorial that covers generating random data with this module.
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:
f.write('\n'.join(passwords))
In all cases, we print out the passwords.
print('\n'.join(passwords))
Related: Build 35+ Ethical Hacking Scripts & Tools with Python EBook
Now let's use the script for generating different password combinations. First, let's print the help:
$ python password_generator.py --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 password_generator.py --total-length 12
uQPxL'bkBV>#
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 password_generator.py --total-length 12 --amount 10
&8I-%5r>2&W&
k&DW<kC/obbr
=/'e-I?M&,Q!
YZF:Lt{*?m#.
VTJO%dKrb9w6
E7}D|IU}^{E~
b:|F%#iTxLsp
&Yswgw&|W*xp
$M`ui`&v92cA
G3e9fXb3u'lc
Awesome! Let's generate a password with 5 lowercase characters, 2 uppercase, 3 digits, and one special character, a total of 11 characters:
$ python password_generator.py -l 5 -u 2 -n 3 -s 1
1'n3GqxoiS3
Okay, generating 5 different passwords based on the same rule:
$ python password_generator.py -l 5 -u 2 -n 3 -s 1 -a 5
Xs7iM%x2ia2
ap6xTC0n3.c
]Rx2dDf78xx
c11=jozGsO5
Uxi^fG914gi
That's great! We can also generate random pins of 6 digits:
$ python password_generator.py -n 6 -a 5
743582
810063
627433
801039
118201
Adding 4 uppercase characters and saving to a file named keys.txt
:
$ python password_generator.py -n 6 -u 4 -a 5 --output-file keys.txt
75A7K66G2H
H33DPK1658
7443ROVD92
8U2HS2R922
T0Q2ET2842
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 password_generator.py -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 over 35 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 ♥
Save time and energy with our Python Code Generator. Why start from scratch when you can generate? Give it a try!
View Full Code Auto-Generate My Code
Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!