歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell 批量添加用戶健壯版

shell 批量添加用戶健壯版

日期:2017/3/1 9:50:19   编辑:SHELL編程

網上傳說,曾經有一道迅雷的筆試題,批量添加用戶。做法很簡單,有個小小的知識點。如何無交互的為用戶設置密碼。有兩種方案:1、expect 2、passwd --stdin 。第一種通用,第二種非RedHat相關版本可能無法使用。大道至簡,用第二種。也看到過網上的相關腳本。感覺不太完善,至少,如果添加的用戶中,原本有一個已經存在,那麼怎麼辦。很多人都沒有處理。對於一個有代碼潔癖的Coder。我決定自己寫一個。上代碼:

#!/bin/bash
#load system functions
[ -f /etc/init.d/functions ] && . /etc/init.d/functions
for i in `seq -w 10`
do
#generate passwd,8 random chars
passwd=`echo $(date +%t%N)$RANDOM|md5sum|cut -c 2-9`
#check wheather the username is in the /etc/passwd
#important awk use the shell variable
check=`awk -F ':' '/^'gccmx$i'/ {print $1}' /etc/passwd`
if [ -z "$check" ];then
useradd gccmx$i &>/dev/null && user_status=$?
echo $passwd | passwd --stdin gccmx$i &>/dev/null && passwd_status=$?
else
user_status=1
passwd_status=1
fi
if [ "$user_status" -eq 0 -a "$passwd_status" -eq 0 ];then
action "The user gccmx$i is add successfully!" /bin/true
echo -e "username:gccmx${i}\tpassword:${passwd}" >>/tmp/userinfo.txt
else
action "The user gccmx$i is add faild!" /bin/false
echo -e "username:gccmx${i}\tpassword:${passwd}" >>/tmp/faild_info.txt
fi
unset user_status && unset passwd_status
sleep 1
done

運行效果(gccmx05,已經存在,所以添加失敗,用戶名密碼信息存儲在/tmp/user_info.txt裡):

Copyright © Linux教程網 All Rights Reserved