linux中批量创建用户脚本示例

时间:2024-02-20 13:09:38

1、 直接创建用户


[root@linuxprobe home]# pwd
/home

[root@linuxprobe home]# ls
a.txt  linuxprobe  software  test.sh
[root@linuxprobe home]# seq -f liujiaxin%02g 10 > a.txt  ## 创建用户列表
[root@linuxprobe home]# cat a.txt
liujiaxin01
liujiaxin02
liujiaxin03
liujiaxin04
liujiaxin05
liujiaxin06
liujiaxin07
liujiaxin08
liujiaxin09
liujiaxin10
[root@linuxprobe home]# bash test.sh
please input passwd for the users:123456   ## 这里需要输入用户密码,批量均为123456
liujiaxin01 has created successfully!
liujiaxin02 has created successfully!
liujiaxin03 has created successfully!
liujiaxin04 has created successfully!
liujiaxin05 has created successfully!
liujiaxin06 has created successfully!
liujiaxin07 has created successfully!
liujiaxin08 has created successfully!
liujiaxin09 has created successfully!
liujiaxin10 has created successfully!

[root@linuxprobe home]# pwd
/home

[root@linuxprobe home]# ls  ## home目录下出现创建的用户
a.txt       liujiaxin01  liujiaxin03  liujiaxin05  liujiaxin07  liujiaxin09  software
linuxprobe  liujiaxin02  liujiaxin04  liujiaxin06  liujiaxin08  liujiaxin10  test.sh

 

2、查看创建用户脚本test.sh

[root@linuxprobe home]# cat test.sh
#!/bin/bash
read -p "please input passwd for the users:" PASSWD
for USERS in `cat a.txt`
do
id $USERS &> /dev/null
if [ $? -eq 0 ]
then
echo "$USERS has existed!"
else
useradd $USERS &> /dev/null
echo $PASSWD | passwd --stdin $USERS &> /dev/null
if [ $? -eq 0 ]
then
echo "$USERS has created successfully!"
else
echo "$USERS has not created successfully!"
fi
fi
done

 

3、删除测试中创建的用户

[root@linuxprobe home]# ls
a.txt       liujiaxin01  liujiaxin03  liujiaxin05  liujiaxin07  liujiaxin09  software  test.sh
linuxprobe  liujiaxin02  liujiaxin04  liujiaxin06  liujiaxin08  liujiaxin10  test2.sh
[root@linuxprobe home]# bash test2.sh  ## 直接运行脚本
liujiaxin01 has removed successfully!
liujiaxin02 has removed successfully!
liujiaxin03 has removed successfully!
liujiaxin04 has removed successfully!
liujiaxin05 has removed successfully!
liujiaxin06 has removed successfully!
liujiaxin07 has removed successfully!
liujiaxin08 has removed successfully!
liujiaxin09 has removed successfully!
liujiaxin10 has removed successfully!
[root@linuxprobe home]# cat test2.sh  ## 查看脚本
#!/bin/bash
for USERS in $(cat a.txt)
do
userdel -r $USERS &> /dev/null
if [ $? -eq 0 ]
then
echo "$USERS has removed successfully!"
else
echo "$USERS has removed failure!"
fi
done

[root@linuxprobe home]# ls
a.txt linuxprobe software test2.sh test.sh