Coming up with a secure password can be a hard task. In this tutorial, we will be simplifying the process of coming up with a password by building a password generator using python.
In this tutorial, we will be using a few python libraries to build our app. Firstly we will use argparse module which is used to make command-line interfaces. Next, we will use the string module to generate different characters such as letters, digits, and punctuation. Lastly, we will use random module to randomize the characters.
Let’s create a file called main.py , inside let’s import these modules as shown below.
import argparse
import random
import string
Next, we need to create a function that will generate our password.
def generate_password(length):
#create a string of all possible characters
characters = string.ascii_letters + string.digits + string.punctuation
# Generate a random password using the characters string
password = ''.join(random.choice(characters) for i in range(length))
return password
The above function takes letters, digits, and punctuations from the string module, and then a password is created by joining the generated characters and randomizing them.
Next, create an argument parser.
parser = argparse.ArgumentParser(description='Generate a random password')
Now add an argument for the password length.
parser.add_argument('length', type=int, help='Length of the password')
Now parse the command line arguments.
args = parser.parse_args()
Now prompt the user to enter the password length.
password_length = args.length
Now let’s call our function and print the password generated.
password = generate_password(password_length)
print(password)
Run the script using the command below.
python3 main.py
Here is the output displayed.
Try as many passwords as possible. Thanks for reading