需求:批量创建10个系统账号,如:test-01到test-10,并且为每一个用户设置密码为随机8位数,同时将创建成功的账号对应密码保存在/tmp/user.txt里,失败则把失败的账号对应密码保存到/tmp/fail_user.txt里

1)批量创建系统账号,没什么特殊的直接使用useradd结合变量
2)随机8位数密码,需要使用到产生随机数的命令,在演示脚本中作者用了以下三条命令结合使用,操作如下:

[root@jason scripts]# echo $(date +%t%N)$RANDOM|md5sum 
142470e2de821875c8e002ba0d2bf4e5  - 
提示:作者分别使用了date,和系统环境变量RANDOM跟md5sum来结合产生随机数

3)前面要求密码为随机8位数,但是前者两个命令结合md5sum会产生128位的固定随机数,文中使用cut命令,来抓取8位随机数,操作如下:

[root@jason ~]# echo $(date +%t%N)$RANDOM|md5sum |cut -c 2-9
3e05cfe6

4)脚本展示

[root@jason scripts]# cat adduser.sh 
#!/bin/sh
[ -f /etc/init.d/functions ]&& . /etc/init.d/functions || exit 1
>/tmp/user.txt
for n in $(seq -w 10)
do
 passwd=`echo $(date +%s%n)$RANDOM|md5sum |cut -c 2-9`
 useradd test-$n >&/dev/null && user_status=$?
 echo "$passwd"|passwd --stdin test-$n >&/dev/null  && pass_status=$?
if [ $user_status -eq 0 -a $pass_status -eq 0 ];then
        action "adduser test-$n" /bin/true
        echo -e "user:\ttest-$n passwd:$passwd" >>/tmp/user.txt
 else
        action "adduser test-$n" /bin/false
        echo -e "user:\ttest-$n passwd:$passwd" >>/tmp/fail_user.txt
fi
done

5)脚本测试

#运行脚本
[root@jason scripts]# sh adduser.sh     
adduser test-01                                            [  OK  ]
adduser test-02                                            [  OK  ]
adduser test-03                                            [  OK  ]
adduser test-04                                            [  OK  ]
adduser test-05                                            [  OK  ]
adduser test-06                                            [  OK  ]
adduser test-07                                            [  OK  ]
adduser test-08                                            [  OK  ]
adduser test-09                                            [  OK  ]
adduser test-10                                            [  OK  ]

#查看创建成功的用户对应的密码
[root@jason scripts]# cat /tmp/user.txt 
user:   test-01 passwd:cd2e36b9
user:   test-02 passwd:98ceb8f4
user:   test-03 passwd:813c5067
user:   test-04 passwd:20e3c58e
user:   test-05 passwd:ed0d93f9
user:   test-06 passwd:67aadb88
user:   test-07 passwd:f399ce9b
user:   test-08 passwd:f32be6f9
user:   test-09 passwd:bfa0cc7a
user:   test-10 passwd:25b6553e

#查看/etc/passwd文件
[root@jason scripts]# tail -10 /etc/passwd
test-01:x:533:533::/home/test-01:/bin/bash
test-02:x:534:534::/home/test-02:/bin/bash
test-03:x:535:535::/home/test-03:/bin/bash
test-04:x:536:536::/home/test-04:/bin/bash
test-05:x:537:537::/home/test-05:/bin/bash
test-06:x:538:538::/home/test-06:/bin/bash
test-07:x:539:539::/home/test-07:/bin/bash
test-08:x:540:540::/home/test-08:/bin/bash
test-09:x:541:541::/home/test-09:/bin/bash
test-10:x:542:542::/home/test-10:/bin/bash