随机密码生成器
Wednesday, January 6th, 2010花了一天时间用Bash写了个生成随机密码的脚本。生成的密码符合以下条件:
- 长度为8~20个字符;
- 包含至少一个大写字母;
- 包含至少一个小写字母;
- 包含至少一个数字;
- 包含至少一个特殊字符。
总的来说,我还是比较喜欢这个脚本的,够简单也够简洁。
PW_LEN=$((8 + (RANDOM % 12))) DIGITS='0 1 2 3 4 5 6 7 8 9' LCHARS='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' UCHARS='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' SCHARS='! @ # $ % ^ & ` ( ) { } [ ] ; : " , . < > ? / \ | ~' DISPTB=(DIGITS LCHARS UCHARS SCHARS) DISPTB_LEN=${#DISPTB[*]} # randomly select one character from randomly selected char table function random_select() { local table=${DISPTB[$((RANDOM % DISPTB_LEN))]} local n_ele= local clist= eval clist=(\$$table) # clist contains char table n_ele=${#clist[*]} # length of array `clist' echo -n ${clist[$((RANDOM % n_ele))]} } function pwgen() { local passwd= for ((cnt=0; cnt<PW_LEN; cnt++)); do passwd=$passwd random_select done echo $passwd } # check whether given password conforms to policy function is_valid() { local pw_len=$(expr length "$1") local nr_lower=$(echo "$1" | fold -w1 | grep -c '[[:lower:]]') local nr_upper=$(echo "$1" | fold -w1 | grep -c '[[:upper:]]') local nr_digit=$(echo "$1" | fold -w1 | grep -c '[[:digit:]]') local nr_schar=$((pw_len - nr_lower - nr_upper - nr_digit)) [ $nr_lower -eq 0 -o $nr_upper -eq 0 -o \ $nr_digit -eq 0 -o $nr_schar -eq 0 ] && return 1 return 0 } while true; do pw=$(pwgen); if is_valid "$pw"; then echo "$pw"; exit 0 fi done