红联Linux门户
Linux帮助

Linux批量添加/删除用户脚本

发布时间:2014-11-04 14:56:24来源:linux网站作者:linux521

说明:蓝色=命令名称

浅绿=命令参数

浅蓝=选项

紫色=目录

系统环境: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