Friday, January 2, 2015

Linux : Bash Random Password Generator

#!/bin/bash
 
passwordLength=20
minNumbers=3
minLowercase=3
minUppercase=3
minSpecial=3
special="!#$%();.@^"
 
checkPassword ()
{
    local lowercase=0 uppercase=0 numbers=0 specialchars=0
 
    if [ ${#p} -ne $passwordLength ]; then return 1; fi
 
    s="$( echo "$p" | tr -cd '0-9' )"; numbers="${#s}"
    s="$( echo "$p" | tr -cd 'a-z' )"; lowercase="${#s}"
    s="$( echo "$p" | tr -cd 'A-Z' )"; uppercase="${#s}"
    s="$( echo "$p" | tr -cd "$special" )"; specialchars="${#s}"
    if [ $numbers -ge $minNumbers -a $lowercase -ge $minLowercase -a $uppercase -ge $minUppercase -a $specialchars -ge $minSpecial ]; then
        return 0
    else
        return 1
    fi
}
 
p=''
while ! checkPassword; do
    p="$( dd if='/dev/urandom' bs=4096 count=1 2>/dev/null | tr -cd "0-9A-Za-z${special}" )"
    p="${p:0:$passwordLength}"
done
echo "$p"

No comments:

Post a Comment