Linux 批量创建和删除用户
Linux 批量创建和删除用户
以 bash
运行下面的脚本可以批量新建指定用户,并为其创建工作目录:
#!/bin/bash
USERS=("aa" "bb") # user names to create
PASSWDS=("aaxx" "bbxx") # corresponding passwords for users
DATA_DIRS=("/hdd" "/ssd") # root data directories
# Get confirmation from user before creation
echo "Do you want to create the following users and their data directories?"
echo "------ users ----------------"
for user in ${USERS[@]}; do
echo "$user"
done
echo "------ root data dirs -------"
for dir in ${DATA_DIRS[@]}; do
echo "$dir"
done
echo "-----------------------------"
echo "(y/n)"
read CONFIRM_DELETE
if [ "$CONFIRM_DELETE" == "y" ]; then
for ((i = 0; i < ${#USERS[@]}; i++)); do
name=${USERS[$i]}
password=${PASSWDS[$i]}
# add user
if id "$name" >/dev/null 2>&1; then
echo "$name" already exists, skip user creation
else
useradd -m "$name"
echo "$name:$password" | chpasswd
echo "Created user $name"
fi
# create data dir
for dir in "${DATA_DIRS[@]}"; do
if [ -d "$dir/$name" ]; then
echo "$dir/$name" already exists, change its owner and group to $name
else
mkdir "$dir/$name" &&
echo "Created directory $dir/$name for $name"
fi
chgrp -R "$name" "$dir/$name"
chown -R "$name:$name" "$dir/$name"
done
echo "-------------"
done
else
echo "Aborting user creation"
fi
tips: 查看所有用户的命令
cat /etc/passwd |cut -f 1,3 -d:
第三个参数:500 以上为新建用户,其它为系统用户
以 bash
运行下面的脚本可以批量删除指定用户
#!/bin/bash
# user names to delete
USERS=("zza" "zzb")
# Get confirmation from user before deleting
echo "Do you want to delete the following users?"
for user in ${USERS[@]}
do
echo "$user"
done
echo "(y/n)"
read CONFIRM_DELETE
# deleting users
if [ "$CONFIRM_DELETE" == "y" ]; then
for user in ${USERS[@]}
do
sudo userdel -r $user
if [ $? -ne 0 ]
then
echo "delete $user failed"
else
echo "delete $user succeed"
fi
done
else
echo "Aborting user deletion"
fi