# Mon Oct 18 04:32:34 EDT 2004 # NAME: randomword # Copyright 2004 Chris F.A. Johnson # Released under the terms of the GNU General Public License description="Generate random passwords; length and characters may be specified" _interspace() { w="$@" _INTERSPACE= while [ ${#w} -gt 0 ] do w_=${w#?} _INTERSPACE="$_INTERSPACE ${w%"$w_"}" w=$w_ done } interspace() { echo $* | sed 's/./& /g' } _randstr() { [ -z "$1" ] && set -- $upper $lower $digits eval "_RANDSTR=\${$(( $RANDOM % $# + 1 ))}" } _randword() { rw_len=${1:-8} _RANDWORD= while [ ${#_RANDWORD} -lt $rw_len ] do _randstr ${charset:-$upper$lower$digits} _RANDWORD=$_RANDWORD$_RANDSTR done } randword() { _randword "$@" && printf "%s\n" "$_RANDWORD" } _rand_word() { [ -z "$fmt" ] && charset=$format _randword ${1:-8} rp_fmt=${fmt:-$_RANDWORD} _RAND_WORD= set -f while [ ${#rp_fmt} -gt 0 ] do rp_=${rp_fmt#?} rp_char=${rp_fmt%"$rp_"} case $rp_char in c) _randstr $consonants ;; d) _randstr $digits ;; f) _randstr $format ;; l) _randstr $lower ;; p) _randstr $punct ;; u) _randstr $upper ;; v) _randstr $vowels ;; C) _randstr $CONSONANTS ;; V) _randstr $VOWELS ;; \\) rp_fmt=$rp_ rp_=${rp_fmt#?} rp_char=${rp_fmt%"$rp_"} _RANDSTR=$rp_char ;; *) _RANDSTR=${rp_fmt%"$rp_"} ;; esac _RAND_WORD=$_RAND_WORD$_RANDSTR rp_fmt=$rp_ done set +f } rand_word() { _rand_word "$@" && printf "%s\n" "$_RAND_WORD" } lower='a b c d e f g h i j k l m n o p q r s t u v w x y z ' upper='A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ' digits='0 1 2 3 4 5 6 7 8 9 ' punct='% # ! @ ? > } | \ = - _ ) ( + * & ^ $ <' format='u l d u l p ' ## these are just for fun vowels='a e i o u ' consonants='b c d f g h j k l m n p q r s t v w x y z ' VOWELS='A E I O U ' CONSONANTS='B C D F G H J K L M N P Q R S T V W X Y Z ' format='u l d u l p v c V C ' fmt= num=1 length= len_lower=6 len_upper=8 charset=$lower_$upper_$digits_$punct opts=n:f:F:l:a: while getopts "$opts" opt do case $opt in a) case $OPTARG in ## list of characters allowed *[!\ \ ][!\ \ ]*) format=`interspace $OPTARG` ;; *) format=$OPTARG ;; esac ;; l) len_lower=${OPTARG%[!0-9]*} ## -l LL,UU lower and upper no. of chars case $len_lower in *[!0-9]*) exit 5 ;; esac len_upper=${OPTARG#*[!0-9]} case $len_upper in *[!0-9]*) exit 5 ;; esac [ $len_lower -gt $len_upper ] && { len_lower=$len_upper len_upper=${OPTARG%[!0-9]*} } ;; n) case $OPTARG in *[!0-9]*) exit 5 ;; esac ## number of passwords to generate num=$OPTARG ;; f) fmt=$OPTARG ;; ## format string .e.g -f ucClvVdpp (see _rand_word() for meanings) F) case $OPTARG in *[!0-9]*) exit 5 ;; esac charset=$format _randword $OPTARG ## all passwords use same format string fmt=$_RANDWORD ;; esac done while [ $num -gt 0 ] do [ $len_upper = $len_lower ] && length=$len_upper || length=$(( $RANDOM % ($len_upper - $len_lower) + $len_lower )) rand_word $length num=$(( $num - 1 )) done