#!/bin/bash
#Function: Add system user from a file list
#Author: Mach
#Email: mach_aly@aliyun.com
#Modify time: 04.10/2017, refactoring
#Modiry time: 04.15/2017, add function Filteruser()
Adduser(){
if [ ! -f $1 ]; then
echo "Error: $1 file non-existent."
exit 1
fi
Filteruser $1
for NM in $(cat $1)
do
useradd $NM && echo "Add user $NM successful."
done
}
Filteruser(){
TimSta=$(date +%F_%T)
for NM in $(cat $1)
do
grep -w "^$NM" /etc/passwd > /dev/null 2>&1
if [ "$?" -eq 0 ]; then
echo -e "user '$NM' has existent.\n" | tee -a ./exisuserlist-$TimSta.log
fi
done
if [ -f exisuserlist-$TimSta.log ]; then
echo "Please handle the above user name.(./exisuserlist-$TimSta.log)"
exit 1
fi
}
Addgroup(){
grep -w "^$2" /etc/group > /dev/null 2>&1
if [ "$?" -ne 0 ]; then
useradd -Ms /bin/fales $2 && echo "Add UNIgroup $2 successful."
echo -e "$(id -gn $2) (unified IDnum group)\n" >> ./newadduserlist.log
fi
for NM in $(cat $1)
do
usermod -G $2 $NM && echo "Add user $NM to group $2 successful."
done
}
PDandlog(){
for NM in $(cat $1)
do
echo -en "$NM\t\t$(id -Gn $NM)\t\t" >> ./newadduserlist.log
PD=`echo $RANDOM | md5sum | head -c 8`
echo $PD | tee -a ./newadduserlist.log | passwd --stdin $NM
echo -e "\n" >> ./newadduserlist.log
done
}
if [ "$UID" -ne 0 ]; then
echo "Error: Need root permission!"
exit 1
fi
case $# in
1)
Adduser $1
PDandlog $1
;;
2)
Adduser $1
Addgroup $1 $2
PDandlog $1
;;
*)
echo "Error: Parameters error."
echo "usage: $0 UserListFile [GroupName]"
;;
esac