sh3.useradd 添加用户脚本
1.写一个脚本:
添加10个用户user1到user10,密码同用户名,但要求只有用户不存在的情况下才能添加
1 #/bin/bash 2 # 3 for i in {1..10};do 4 if id user$i &> /dev/null;then 5 echo "user$i exists." 6 else 7 useradd user$i 8 echo user$i | passwd --stdin user$i &> /dev/null 9 echo "Add user$i finished!" 10 fi 11 done 12 ~
2. 删除用户脚本
#/bin/bash # for i in {1..10};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
其它:退出
1 #/bin/bash 2 # 3 if [ $# -lt 1 ];then 4 echo "Usage:adminiuser ARG" 5 exit 8 6 fi 7 8 if [ $1 == 'add' ];then 9 for i in {1..10};do 10 if id user$i &> /dev/null;then 11 echo "user$i is exists" 12 else 13 useradd user$i 14 echo user$i | passwd --stdin user$i &> /dev/null 15 echo "Add user$i finished." 16 fi 17 done 18 elif [ $1 == 'del' ];then 19 for i in {1..10};do 20 if id user$i &> /dev/null;then 21 userdel -r user$i 22 echo "Del user$i finished." 23 else 24 echo "NO user$i" 25 fi 26 done 27 else 28 echo "Unknown ARG" 29 exit 9 30 fi
4.优化版本:
自选添加或删除多用户
admin add user1,user2,user3
admin del user1,user2,user3
1 #/bin/bsh 2 # 3 if [ $# -lt 1 ];then 4 echo "Usage:ARG" 5 exit 3 6 fi 7 if [ $1 == 'add' ];then 8 for i in `echo $2 | sed 's/,/ /g'`;do 9 if id $i &> /dev/null;then 10 echo "user $i exists." 11 else 12 useradd $i 13 echo $i | passwd --stdin $i &> /dev/null 14 echo "Add user $i finished!" 15 fi 16 done 17 elif [ $1 == 'del' ];then 18 for i in `echo $2 | sed 's/,/ /g'`;do 19 if id $i &> /dev/null;then 20 userdel -r $i 21 echo "Del user $i finshed!" 22 else 23 echo "user $i exists." 24 fi 25 done 26 elif [ $1 == '--help' ];then 27 echo " Your want add-user 'adminuser add username1,name2..!'. 28 Your want del-user'adminuser del username1,name2..!'" 29 else 30 echo "Unknow ARG??? --help " 31 fi 32 33 注: echo aa,bb,cc | sed 's/,/ /g' 34 用sed替换命令把‘aa,bb,cc’ 转成列表式,再给for循环调用