sh3.useradd 添加用户脚本

时间:2023-03-08 17:05:11

1.写一个脚本:

添加10个用户user1到user10,密码同用户名,但要求只有用户不存在的情况下才能添加

 #/bin/bash
#
for i in {..};do
if id user$i &> /dev/null;then
echo "user$i exists."
else
useradd user$i
echo user$i | passwd --stdin user$i &> /dev/null
echo "Add user$i finished!"
fi
done
~

2. 删除用户脚本

#/bin/bash
#
for i in {..};do
if id user$i &> /dev/null;then
userdel user$i
echo "user$i is delete!"
else
echo "user$i is no have!"
fi
done

userdel(选项)(参数)

-f:强制删除用户,即使用户当前已登录;

-r:删除用户的同时,删除与用户相关的所有文件。

3.扩展:

接受一个参数:

add: 添加用户 user1..user10

del:删除用户 user1..user10

其它:退出

 #/bin/bash
#
if [ $# -lt ];then
echo "Usage:adminiuser ARG"
exit
fi if [ $ == 'add' ];then
for i in {..};do
if id user$i &> /dev/null;then
echo "user$i is exists"
else
useradd user$i
echo user$i | passwd --stdin user$i &> /dev/null
echo "Add user$i finished."
fi
done
elif [ $ == 'del' ];then
for i in {..};do
if id user$i &> /dev/null;then
userdel -r user$i
echo "Del user$i finished."
else
echo "NO user$i"
fi
done
else
echo "Unknown ARG"
exit
fi

4.优化版本:

自选添加或删除多用户

admin add user1,user2,user3

admin del user1,user2,user3

 #/bin/bsh
#
if [ $# -lt ];then
echo "Usage:ARG"
exit
fi
if [ $ == 'add' ];then
for i in `echo $ | sed 's/,/ /g'`;do
if id $i &> /dev/null;then
echo "user $i exists."
else
useradd $i
echo $i | passwd --stdin $i &> /dev/null
echo "Add user $i finished!"
fi
done
elif [ $ == 'del' ];then
for i in `echo $ | sed 's/,/ /g'`;do
if id $i &> /dev/null;then
userdel -r $i
echo "Del user $i finshed!"
else
echo "user $i exists."
fi
done
elif [ $ == '--help' ];then
echo " Your want add-user 'adminuser add username1,name2..!'.
Your want del-user'adminuser del username1,name2..!'"
else
echo "Unknow ARG??? --help "
fi 注: echo aa,bb,cc | sed 's/,/ /g'
用sed替换命令把‘aa,bb,cc’ 转成列表式,再给for循环调用