首页 > linux > 编写删除用户脚本(交互)

编写删除用户脚本(交互)

作者:bin

脚本如下

function get_answer 
{
 unset ANSWER
 while [ -z $ANSWER ]
 do
     echo -e $1;
     read -t 10 ANSWER
 done
}

function process_answer
{
 case $ANSWER in 
 y|Y|yes|YES)
 return 0 ;;
 *)
    echo "Please enter y|Y|yes|YES";
    return -1;;
 esac
}

function check_name
{
 USER_COUNT_RECODE=$(cat /etc/passwd | grep -w $1)
 if [ -z $USER_COUNT_RECODE ] 
 then
    return -1;
 else 
    return 0;
 fi
}

function go
{

#检查当前是否是root用户
 if [ "root" != $(whoami) ]
 then
     echo
     echo "Please run this script with root"
     exit;
 fi

#获取用户输入的名称
 get_answer "Please enter delete name of the user:\c"
 USERNAME=$ANSWER

#检查用户是否存在
 check_name $USERNAME 
 if [ $? -eq 0 ] 
 then 
     echo -e "this is the account record:\n"
     echo -e $USER_COUNT_RECODE."\n"
     else
     echo "can not find this account '$ANSWER' from system";
     go;
 fi

#确认是否是这个用户
 get_answer "Is this the correct User Account ?[y/n]"
 process_answer 
 if [ $? -ne 0 ] 
 then
     go;
 fi

#删除用户进程
 if [ -z $(ps -u $USERNAME --no-heading|gawk '{print $1}'|xargs -d \\n /bin/kill -9) ]
 then
     echo "process killed"
 else
     go;
 fi

#整理用户文件
 echo "start to find file of $USERNAME"
 find / -user $USERNAME>$USERNAME"_File.rpt" 2>/dev/null & 
 while [ 1 ]
 do
     job=$(jobs | gawk '!/Running/{print 0}')
 if [ "$job" == "0" ]
 then
     break
 fi
 echo -e ".\c";
 sleep 0.5;
 done
 echo

#最后一次询问是否删除用户
 get_answer "Remove $USERNAME account from system?[y/n]"
 process_answer
 if [ $? -eq 0 ]
 then
     userdel $USERNAME
     echo
     echo "User account $USERNAME has been removed"
     exit;
 fi
 go;
}
go

您必须 [ 登录 ] 才能发表留言!