Linux上批量创建账号

应用背景

假设要创建5个账号,分别是cakin{1,2,3,4,5},且这5个账号未来要想共享一个目录,因此应该加入通一个用户组,假设这个用户组为cakingroup,且这5个账号的密码均为password,那么如何创建这5个账号?

解决方案

第一步:创建useradd.sh脚本

[root@localhost ~]# pwd

/root

[root@localhost ~]# mkdir bin

[root@localhost ~]# cd /root/bin

[root@localhost bin]# vim useradd.sh

#!/bin/bash

groupadd cakingroup

for username in cakin1 cakin2 cakin3 cakin4 cakin5

do

        useradd -G cakingroup $username

        echo "password" | passwd --stdin $username

done

第二步:执行useradd.sh脚本

[root@localhost bin]# sh useradd.sh

Changing password for user cakin1.

passwd: all authentication tokens updated successfully.

Changing password for user cakin2.

passwd: all authentication tokens updated successfully.

Changing password for user cakin3.

passwd: all authentication tokens updated successfully.

Changing password for user cakin4.

passwd: all authentication tokens updated successfully.

Changing password for user cakin5.

passwd: all authentication tokens updated successfully.

第三步:利用id命令查询组的支持是否正确

[root@localhost bin]# id cakin1

uid=1001(cakin1) gid=1002(cakin1) groups=1002(cakin1),1001(cakingroup)

[root@localhost bin]# id cakin2

uid=1002(cakin2) gid=1003(cakin2) groups=1003(cakin2),1001(cakingroup)