BASH - Generate-Password.sh

From IT-Arts.net
Revision as of 16:23, 16 December 2025 by Admin (talk | contribs)



Script

#!/bin/bash
#
# Script based on pwgen package, where :
#
# -N, --num-passwords=num | Generate num passwords.
#
# -s, --secure | Generate completely random, hard-to-memorize passwords.
#                These should only be used for machine passwords, since otherwise 
#                it's almost guaranteed that users will simply write the password
#                on a piece of paper taped to the monitor...
#
# -y, --symbols | Include at least one special character in the password.
#
# $1, '-y' option or password length
#
# $2, password length if '-y' option is used

exclude_chars="iI1oO0"

# Function to filter out excluded characters
filter_password() {
    local password=$1
    for char in $(echo $exclude_chars | sed 's/\(.\)/\1 /g'); do
        password=$(echo $password | tr -d $char)
    done
    echo $password
}

# Function to regenerate password until it reaches desired length
generate_password() {
    local length=$1
    local include_symbols=$2
    local password=""
    
    while true; do
        if [ "$include_symbols" == "yes" ]; then
            # Generate password with symbols (using -y option of pwgen)
            password=$(pwgen -N 1 -s -y $length)  # The -y option guarantees at least one symbol
        else
            # Generate password without symbols
            password=$(pwgen -N 1 $length)
        fi

        # Apply the filter to exclude unwanted characters
        filtered_password=$(filter_password "$password")

        # If the filtered password is long enough, return it
        if [ ${#filtered_password} -ge $length ]; then
            echo $filtered_password
            break
        fi
    done
}

if [ "$1" = "-y" ]; then
    # Generate password with symbols and filter unwanted characters
    password=$(generate_password "$2" "yes")
    echo "PASSWORD WITH SPECIAL CHARS : "
    echo $password

elif [[ "$1" =~ ^[0-9]+$ ]]; then
    # Generate password without symbols and filter unwanted characters
    password=$(generate_password "$1" "no")
    echo "PASSWORD WITHOUT SPECIAL CHARS : "
    echo $password

else
    echo "USAGE: ./this-script.sh <'-y' for symbols> <Password Length integer>"
fi

exit 0

Source

This script is based on Package:

pwgen
Version: 2.08-2
Installed-Size: 51
Maintainer: Theodore Y. Ts'o <tytso@mit.edu>
Architecture: amd64
Depends: libc6 (>= 2.14)
Description-en: Automatic Password generation
 pwgen generates random, meaningless but pronounceable passwords.
 These passwords contain either only lowercase letters, or upper
 and lower case mixed, or digits thrown in.
 Uppercase letters and digits are placed in a way that eases
 remembering their position when memorizing only the word.