Friday, July 24, 2009

Generate random password with shell script.

Generate random passwords
Generate random passwords consist of letters, numbers and any special characters.
$ tr -cd \#_[:alnum:] < /dev/urandom |  fold -w 8 | head -5 
shu6_BEN
BIL2b#0w
xgHWgOJ2
E1NmtxX1
WqcTAsRN

or

$openssl passwd "$RANDOM" | cut -c1-8
cH75S94U



Pick the appropriate password
The above one liner is fine for general purpose, but with password policy, you have to choose one adheres to the password policy

The following script will pick the right password in form of at least 1 upper case, 1 lower case and 1 digit

#!/bin/bash
# Generate random password adhere to password policy
# caveat: if you need more strict policy e.g. 2 upper cases,2 lower cases, 2 digit, adjust the number retuned by head
LENGTH=8
MIN_U=1
MIN_L=1
MIN_D=1

for i in $(tr -dc [:alnum:] </dev/urandom |  fold -w $LENGTH |  head -20)
do
UPPERS=$(echo $i |  $AWK '{print gsub(/[A-Z]/,"")}')
LOWERS=$(echo $i |  $AWK '{print gsub(/[a-z]/,"")}')
DIGITS=$(echo $i |  $AWK '{print gsub(/[0-9]/,"")}')
if [ $UPPERS -ge $MIN_U -a $LOWERS -ge $MIN_L -a $DIGITS -ge $MIN_D ];then
FOUND=1; break
fi
done

if [  -z $FOUND ];then
echo "ERROR: could not generate appropriate password"
else
echo "Password Generated :" $i
fi


$ ./genpwd.sh
Password Generated : 8sZrR1az

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.