Shell脚本:批量添加用户,并设置随机字符为密码

练习shell脚本题目:写一个脚本,实现批量添加20个用户,用户名为user1-20,密码为user后面跟5个随机字符;

之前练习过批量创建用户,使用for循环就可以实现,这次多了一个需求,设置用户密码,密码为user后面跟5个随机字符。思路为:创建用户当然还是使用for循环,随机字符需要研究一下怎么生成,怎么在脚本里面设置密码?

下面是经过我测试多次,实现题目需求的脚本,大家有更好的可以贴出来,共同学习。

[root@localhost ~]# cat user.sh
#!/bin/bash
#writen by mofansheng @2015-08-04
for i in `seq 1 20`
do
  pw=`echo $[$RANDOM]|md5sum|cut -c 1-5`
  useradd user$i
  echo "user$i $pw" >> /root/pw.txt
  echo "user$pw" |passwd --stdin user$i
done

提醒注意:生成随机密码后直接给用户设定了,但是我并不知道随机密码是什么啊。所以加了一个随机密码定向到一个文件中,方便管理。格式为:用户名 后面跟随机字符;举例如下:

[root@localhost ~]# cat pw.txt
user1 3e9db
user2 febb6
user3 43c55

其他生成随机字符的方法:

1:生成的随机字符为字母加数字组合

[root@localhost ~]# cat /dev/urandom | head -1|md5sum |head -c 5
cf93d
[root@localhost ~]# cat /dev/urandom | head -1|md5sum |head -c 5
75217


2:生成的随机字符包含特殊字母

[root@localhost ~]# cat /dev/urandom | strings -n 5 | head -n 1
O4%"G
[root@localhost ~]# cat /dev/urandom | strings -n 5 | head -n 1
mMSxu

猜你喜欢

转载自www.linuxidc.com/Linux/2015-08/122112.htm