最近进度有点慢,跟着《私房菜》学习进行到了Linux ACL权限设置这一章节,由于书中经常有加账号和删除账号的操作,就觉得太繁琐了,正好可以拿这个来继续巩固下前一章脚本编写的基础。话不多说进入正题。
本脚本实现的功能是根据用户输入的选项来选择是“添加”还是“删除”账号,以下是脚本代码。
#!/bin/bash #Program: # This program will batch add accounts. #History: #2016/04/14 MG First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH echo "Input your operation:" #选项说明 echo "1.Option 1 is add user account." echo "2.Option 2 is del user account." echo "" while [ -z "$op" ] #进行判断用户是否有输入 do read -p "Enter your operation: " op #用户输入选项 done case $op in #对操作进行判断 "1") while [ -z "$usr" ] #判断用户输入账号名是否为空 do read -p "Input your user account: " usr done read -p "input add quantity: " nu chg=$(cut -d: -f1 /etc/passwd |grep $usr) #搜索系统是否有该账号 if [ "$chg" == "" ];then read -p "input add quantity: " nu #输入要创建的账号 nu=${nu:-1} #如果用户没输入则默认为一个 for (( i=1;i<=$nu;i++ )) do # echo $usr$i useradd -c "$usr$i" $usr$i echo "$usr$i"|passwd --stdin $usr$i # 批量为用户添加密码,不显示添加后的回显信息 chage -d 0 $usr$i #强制新用户第一次登陆时更改密码 done echo "$nu accounts added successfully!" else echo "The user $usr account is exist." exit 1 fi ;; "2") read -p "Enter your account: " users if [ ! -z "$users" ];then usr=$(grep $users /etc/passwd |cut -d: -f1) for user in $usr do # echo $user read -p "Are you sure to del this account?" yn if [ "$yn" == "y" -o "$yn" == "Y" ];then userdel -r $user && echo "$user accont deleted successfully!"|| echo "Delete failed!" else echo "You have cancel this operation." exit 0 fi done fi ;; esac
该脚本还是不够完善,比如创建账号的时候如果之中存在了“test"账号,那就无法以test为开头创建test2等等账号了,还有一些其他的问题等之后再慢慢补充吧,每天写一点就会有进步。
(PS. 英文太差凑活看吧,都是中式英语o(╯□╰)o)
时间: 2024-10-10 21:35:31