Movatterモバイル変換


[0]ホーム

URL:


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 apr 2023 ·Ethical Hacking ·Cryptography

Unlock the secrets of your code with ourAI-powered Code Explainer. Take a look!

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 willuse theargparse 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.

Imports

Let us import some modules. For this program, we just need theArgumentParser class fromargparse and therandom andsecrets modules. We also get thestring 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 ArgumentParserimport secretsimport randomimport string

If you're not sure how therandom andsecrets modules works. Checkthis tutorial that covers generating random data with these modules.

Get: Build 35+ 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 theArgumentParser class to ourparser 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 Parserparser = 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 asint:

# Adding the arguments to the parserparser.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 argumentparser.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. Theamount 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 theparse_args() method of theArgumentParser 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 thepasswords list that will hold all the generated passwords:

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

In thefor loop, we first check whethertotal_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 thesecrets module instead of the random so we can generate cryptographically strong random passwords, more inthis tutorial.

Otherwise, we make apassword 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 thepassword list. For each of the types, we check if it's passed to the parser. We get the respective letters from thestring 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 therandom.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 thispassword to thepasswords list.

        # append this password to the overall list of password.        passwords.append(password)

Again, if you're not sure how the random module works, checkthis 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:        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

Examples

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

$ python password_generator.py --helpusage: 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 12uQPxL'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%dKrb9w6E7}D|IU}^{E~b:|F%#iTxLsp&Yswgw&|W*xp$M`ui`&v92cAG3e9fXb3u'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 11'n3GqxoiS3

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

$ python password_generator.py -l 5 -u 2 -n 3 -s 1 -a 5Xs7iM%x2ia2ap6xTC0n3.c]Rx2dDf78xxc11=jozGsO5Uxi^fG914gi

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

$ python password_generator.py -n 6 -a 5 743582810063627433801039118201

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

$ python password_generator.py -n 6 -u 4 -a 5 --output-file keys.txt75A7K66G2HH33DPK16587443ROVD928U2HS2R922T0Q2ET2842

A newkeys.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

Conclusion

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 codehere.

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

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

Happy coding ♥

Just finished the article? Now, boost your next project with ourPython Code Generator. Discover a faster, smarter way to code.

View Full Code Build My Python Code
Sharing is caring!



Read Also


How to Generate Random Data in Python
How to Extract Saved WiFi Passwords in Python
How to Extract Chrome Passwords in Python

Comment panel

    Got a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!





    Ethical Hacking with Python EBook - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags

    Ethical Hacking with Python EBook - Topic - Middle


    New Tutorials

    Popular Tutorials


    Ethical Hacking with Python EBook - Topic - Bottom

    CodingFleet - Topic - Bottom






    Claim your Free Chapter!

    Download a Completely Free Ethical hacking with Python from Scratch Chapter.

    See how the book can help you build awesome hacking tools with Python!



    [8]ページ先頭

    ©2009-2025 Movatter.jp