您的位置:首页 > 职场人生

批量 添加/删除 用户脚本

2012-01-16 11:10 489 查看
说明:蓝色=命令名称

浅绿=命令参数
浅蓝=选项
紫色=目录
系统环境:CentOS 6.2 i686
添加脚本:
#!/bin/bash

PWD=users.txt
PASSWD=123456

while getopts "d:p:h" opt
do
case $opt in
h)
cat << EOF
Useing Option:
-d a txt for users,default ./users.txt
-p users password, default 123456
-h help infomation
EOF
exit;
;;
d)
PWD=$OPTARG
;;
p)
PASSWD=$OPTARG
;;
*)
echo "Unkonw argument! Please use -h for help."
exit;
esac
done

if test -f "$PWD"
then
for i in `cat $PWD`
do
USER=`awk -F ":" '{if($1~/peixun_'"$i"'/) print $1}' /etc/passwd`
#if ["$USER" != "peixun_$1"];
#echo "`awk -F ":" '{if($1~/peixun_'"$i"'/) print $1}' /etc/passwd`"
if test -z "`awk -F ":" '{if($1~/peixun_'"$i"'/) print $1}' /etc/passwd`"
then
useradd -m peixun_$i
echo "$PASSWD"|passwd --stdin peixun_$i &> /dev/null
echo "USER:peixun_$i PASSWD:$PASSWD"
echo "`date +"%Y-%m-%D %H%M%S"` USER:peixun_$i PASSWD:$PASSWD" >> /var/log/adduser.log
else
echo "User peixun_$i is exists"
fi
done
else
echo "not found $PWD"
exit;
fi

删除脚本:

#!/bin/bash

del_users_only(){
for i in $USERS
do
userdel $i
echo "USER:$i"
echo "`date +'%Y-%m-%d %H:%M:%S'` USER:$i" >> /var/log/deluser.log
done
}

del_users_home(){
for i in $USERS
do
HOME=`awk -F ":" '{ if($1~/test/) print $6}' /etc/passwd`
userdel -r $i
echo "USER:$i del HOME:$HOME"
echo "`date +'%Y-%m-%d %H:%M:%S'` USER:$i del HOME:$HOME" >> /var/log/deluser.log
done
}

select_y_n_2(){
echo "Do you want to del HOME?(y/n)"
read yn2
case $yn2 in
n|N)
del_users_only;
;;
y|Y)
del_users_home;
;;
*)
echo "Please enter y or n"
select_y_n_2;
esac
}

select_y_n_1(){
echo "del USERS:$USERS"
echo "Do you want to del USERS?(y/n)"
read yn1
case $yn1 in
n|N)
exit;
;;
""|y|Y)
select_y_n_2;
;;
*)
echo "Please enter y or n"
select_y_n_1;
esac
}

if test -z "$1" ||[ "$1" = "-" ]||[ "${1:0:1}" != "-" ]
then
echo "Unkonw argument! Please use -h for help."
exit;
else
while getopts "u:h" opt
do
case $opt in
""|h)
cat << EOF
Useing Option:
-u keywork for users
-h help infomation
EOF
exit;
;;
u)
WORD=$OPTARG
;;
?)
echo "Unkonw argument! Please use -h for help."
exit;
esac
done

USERS=`awk -F ":" '$3>=500&&$1~/'"$WORD"'/ {print $1}' /etc/passwd`

if test -z "$USERS"
then
echo "Users are not found!"
exit;
else
select_y_n_1
fi
fi
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息