Python Code for Random Password Generator

In this blog, I will provide a Python script to generate a random password of a specified length. The script primarily uses two Python modules, random and string, to generate randomized passwords.

The string module provides predefined sets of characters such as lowercase letters (ascii_lowercase), uppercase letters (ascii_uppercase), digits (digits), and special characters (punctuation). Using these character sets, the script ensures that the password contains at least one character from each of these four groups. The remaining characters are then randomly selected from all groups combined.

The random module is used to shuffle the characters to ensure that no predictable patterns emerge and that characters from the four groups are distributed randomly throughout the password.

Here is the Python script:

import sys
import random
import string


def generate_password(pass_length):
    """
    this function uses string module of python to generate a random password
    """
    # get characters using string module
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    digits = string.digits
    special = string.punctuation
    all_characters = lower + upper + digits + special

    # Ensure the password includes at least one character from each category
    rand_password = [
        random.choice(lower),
        random.choice(upper),
        random.choice(digits),
        random.choice(special)
    ]

    # select the remaining characters from the whole group
    rand_password += random.choices(all_characters, k=pass_length - 4)

    # Shuffle the password to make it more random
    random.shuffle(rand_password)
    return ''.join(rand_password)


def main():
    """
    random password generator in Python
    """
    # provide the password length as command-line argument
    args = sys.argv

    # check if user provided a value or not
    if len(args) < 2:
        print("please provide password length as command-line argument")
    else:
        val = int(args[1])
        if val < 8:
            print("this program generates password of at least 8 characters, so provide a value >=8")
        else:
            generated_password = generate_password(val)
            print(f"your random password of length {len(generated_password)}: {generated_password}")

if __name__ == "__main__":
    main()

Save the code in a file named password_generator.py (or any name you prefer). Run the script in your terminal, providing the desired password length (>=8) as a command-line argument, as shown below. The script will generate and display a random password with its length.

python password_generator.py 15

Please let me know in the comments if you find any errors in the code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.