Advertisement

Shell Script For Password Generator Script

Linux Shell Script For Password Generator Script

Password Generator Script :

#!/bin/bash
length=12
# Generate a random password
password=$(openssl rand -base64 $length)
echo "Generated password: $password"


Shell script that generates random passwords using openssl

#!/bin/bash

# Function to generate random password
generate_password() {
    local length="$1"
    openssl rand -base64 $((length * 3 / 4)) | head -c $length
}

# Default password length
DEFAULT_LENGTH=12

# Read password length from user input
read -p "Enter the length of the password (default is $DEFAULT_LENGTH): " length
if [ -z "$length" ]; then
    length=$DEFAULT_LENGTH
fi

# Generate password
password=$(generate_password $length)

echo "Generated Password: $password"

Explanation:

  1. Function generate_password:

    • Uses openssl rand -base64 to generate random bytes and then converts them to base64 encoding.
    • Adjusts the number of bytes generated ($((length * 3 / 4))) to ensure the output length is close to the desired password length.
    • head -c $length ensures the final password length is exactly $length.
  2. Default Password Length:

    • DEFAULT_LENGTH=12: Sets the default password length to 12 characters.
  3. Reading Input:

    • Prompts the user to enter the desired password length.
    • If no input is provided (-z "$length"), defaults to DEFAULT_LENGTH.
  4. Generating and Displaying Password:

    • Calls generate_password function with the specified or default length.
    • Stores the generated password in the password variable.
    • Prints the generated password to the console.

Usage:

  • Save the script in a file (e.g., password_generator.sh) and make it executable (chmod +x password_generator.sh).
  • Run the script (./password_generator.sh) to generate a random password.
  • Follow the prompts to specify a custom password length or press Enter to use the default length.

Notes:

  • This script uses openssl for generating random bytes, which is available by default on most Unix-like systems.
  • Adjust the DEFAULT_LENGTH variable to set your preferred default password length.
  • For more secure or complex password requirements, consider additional validations or checks in the script, such as ensuring a minimum length or including specific character types.

Post a Comment

0 Comments