题目:用shell脚本批量创建用户stu01-stu10,并生成8个字符的随机密码

一、解题思路:

1、在linux系统下添加用户命令--useradd

 useradd stu01

2、非交互式给用户设置密码

 echo "123456" | passwd --stdin stu01

3、数字前加0

 {01..10}

3、随机生成8位字符串

 echo $RANDOM | md5sum | cut -c 1-8   

4、循环的思路添加用户

for ;do ;done

二、开发shell脚本:

#!/bin/bash#Desctiption: Create 10 users in batches and randomly generate 8-character passwords#加载系统函数库,用到action函数[ -f /etc/init.d/functions ] && source /etc/init.d/functions#判断是否当前用户是否为root用户if [ $UID -ne 0 ];then  echo "Pls run this script by root"  exit 1fi#批量创建用户for user in stu{01..10}  do    #判断要创建的用户是否已经存在。如果存在,给出错误提示,继续下一次循环    num=$(grep -w "$user" /etc/passwd | wc -l)    if [ $num -ne 0 ];then      action "useradd: user $user already exists" /bin/false      continue    fi    #生成8为随机字符,并赋值给变量pass    pass=$(echo $RANDOM | md5sum | cut -c 1-8)    #循环创建用户,成功之后执行下一条语句    useradd $user && \    #非交互设置用户密码,不打印输出    echo $pass | passwd --stdin $user >/dev/null 2>&1    #判断用户是否创建成功    RETVEL=$?    if [ $RETVEL -eq 0 ];then         action "useradd: $user successfully" /bin/true      else         action "useradd: $user failed" /bin/false    fi    #将用户名和密码写入到/tmp/passwd.txt文件当中    echo -e "$user\t$pass" >> /tmp/passwd.txtdone

三、测试结果

[root@lt1 script]# sh add_user.sh useradd: stu01 successfully                                [  OK  ]useradd: stu02 successfully                                [  OK  ]useradd: stu03 successfully                                [  OK  ]useradd: stu04 successfully                                [  OK  ]useradd: stu05 successfully                                [  OK  ]useradd: stu06 successfully                                [  OK  ]useradd: stu07 successfully                                [  OK  ]useradd: stu08 successfully                                [  OK  ]useradd: stu09 successfully                                [  OK  ]useradd: stu10 successfully                                [  OK  ][root@lt1 script]# cat /tmp/passwd.txt stu01	2bc5773dstu02	f2ad5e18stu03	f3a84bd0stu04	535c4aa9stu06	8261bae6stu07	caba66a8stu08	44db0f2cstu09	c3f0a1d8stu10	c622b950

测试成功!