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

4 comments:

  1. Hi

    I am new to expect. Please if any one can help on my issue its really appreciable. here is my issue:

    I want expect script for random passwords and random commands generation.

    please can anyone help me?

    Many Thanks in advance

    ReplyDelete
  2. help me ...
    Write a shell script setup linux security policies include:
    1. password policy
    2. User policy
    3. firewall
    Note: Create a file.sh from 1 to 3. purposes:
    If (1) successful
    then 2
    If (2) successful
    then 3
    End

    ReplyDelete
  3. error not ruming

    ./test.sh
    ./test.sh: line 11: {print gsub(/[A-Z]/,"")}: No such file or directory
    ./test.sh: line 12: {print gsub(/[a-z]/,"")}: No such file or directory
    ./test.sh: line 13: {print gsub(/[0-9]/,"")}: No such file or directory
    ./test.sh: line 14: [: too many arguments
    ...
    ERROR: could not generate appropriate password

    ReplyDelete
    Replies
    1. replace $AWK with the full path of the awk command

      Delete