1.1 脚本案例
批量创建20个用户,用户名为user1-user20,并生成8位随机登录密码,用户组采用键盘输入的方式,并将用户名及登录密码保存到/tmp/create_user.txt普通文件中。
1.2 脚本名称
1.3 脚本代码
#!/bin/bash
read -p "Please input your user_group:" group_name
groupadd $group_name
for user in `echo user{1..20}`;
do
useradd -g $group_name $user
pass=$((RANDOM+10000000))
echo "$pass" | passwd --stdin $user > /dev/null 2>&1 && history -c
echo -e "$user $pass $group_name" > /tmp/create_user.txt
done
1.4 脚本运行方法
#执行创建用户脚本
[root@localhost ~]# /bin/sh /tmp/create_user.sh
Please input your user_group:kaifa
#验证用户和组是否创建成功
[root@localhost ~]# grep "^user*" /etc/passwd
user1:x:1037:1037::/home/user1:/bin/bash
user2:x:1038:1037::/home/user2:/bin/bash
user3:x:1039:1037::/home/user3:/bin/bash
user4:x:1040:1037::/home/user4:/bin/bash
user5:x:1041:1037::/home/user5:/bin/bash
user6:x:1042:1037::/home/user6:/bin/bash
user7:x:1043:1037::/home/user7:/bin/bash
user8:x:1044:1037::/home/user8:/bin/bash
user9:x:1045:1037::/home/user9:/bin/bash
user10:x:1046:1037::/home/user10:/bin/bash
user11:x:1047:1037::/home/user11:/bin/bash
user12:x:1048:1037::/home/user12:/bin/bash
user13:x:1049:1037::/home/user13:/bin/bash
user14:x:1050:1037::/home/user14:/bin/bash
user15:x:1051:1037::/home/user15:/bin/bash
user16:x:1052:1037::/home/user16:/bin/bash
user17:x:1053:1037::/home/user17:/bin/bash
user18:x:1054:1037::/home/user18:/bin/bash
user19:x:1055:1037::/home/user19:/bin/bash
user20:x:1056:1037::/home/user20:/bin/bash
[root@localhost ~]# grep "kaifa" /etc/group
kaifa:x:1037:
#查看创建的用户及对应用户的8位随机密码
[root@localhost ~]# cat /tmp/create_user.txt
user1 10020135 kaifa
user2 10018434 kaifa
user3 10004073 kaifa
user4 10018115 kaifa
user5 10016417 kaifa
user6 10030208 kaifa
user7 10018870 kaifa
user8 10030613 kaifa
user9 10011175 kaifa
user10 10017527 kaifa
user11 10021220 kaifa
user12 10007388 kaifa
user13 10020800 kaifa
user14 10002884 kaifa
user15 10028439 kaifa
user16 10010083 kaifa
user17 10008170 kaifa
user18 10002190 kaifa
user19 10030764 kaifa
user20 10014551 kaifa
1.5 附录
1.5.1 批量删除用户和组命令:
[root@localhost ~]# for user in `echo user{1..20}`;do userdel -r $user; done
[root@localhost ~]# groupdel kaifa