linux批量建立使用者帳號指令碼,linux使用者帳號指令碼
在啃鳥哥的linux私房菜這本書,看到後面發現前面學的漸漸忘記了. 為了熟悉一些命令, 練習一下shell指令碼 在14章看到的批量建立帳號範例,就學著,寫一下練練手。 下面的代碼有注釋 照著鳥哥寫的,稍加改動 符合學校的編製。
一.大量建立帳號並將資訊儲存至檔案
沒有像書上提供可選擇密碼產生方式,密碼是和帳號一樣,並設定了登入以後強制使用者更改密碼,覺得這種方案更安全
1 #!/bin/bash 2 # 3 #this program use to add account for your linux 4 #referece: vbird's private dish. 5 # 6 #History: 2017/04/13 7 8 9 #儲存帳號密碼檔案10 accountfile="user.passwd"11 12 read -p "輸入年級:如(2015):" username_grade13 read -p "輸入班級號:如(1122):" username_class14 read -p "輸入編號位元:如(2):" nu_nu15 read -p "輸入起始號碼:如(1):" nu_start16 read -p "輸入帳號數量:如(10):" nu_amount17 18 if [ "$username_grade" == "" -o "username_class" == "" ]; then 19 echo "請輸入年級班級資訊!";20 exit 121 fi22 23 #判斷數字是否合法24 testing0=$(echo $nu_nu | grep '^0-9')25 testing1=$(echo $nu_start | grep '^0-9')26 testing2=$(echo $nu_amount | grep '^0-9')27 28 if [ "$testing0" != "" -o "$testing1" != "" -o "$testing2" != "" ]; then29 echo "輸入的數字不對!";30 exit 131 fi 32 33 #如果檔案存在重新命名加上日期34 [ -f "$accountfile" ] && mv $accountfile "$accountfile"$(date +%Y%m%d%s)35 36 nu_end=$(($nu_start+$nu_amount-1))37 38 for((i=$nu_start; i<=$nu_end; i++))39 do 40 #${i} 統計數字i的長度41 nu_len=${#i}42 if [ $nu_nu -lt $nu_len ]; then43 echo "輸入不合理,編號位元不足或帳號數量過多!"44 echo "please check it out"45 exit 146 fi47 48 #需要在編號前面補零的位元49 nu_diff=$(($nu_nu - $nu_len))50 51 nu_nn=""52 if [ "$nu_diff" != "0" ]; then53 nu_nn=000000000054 nu_nn=${nu_nn:1:$nu_diff}55 fi56 57 #將以上資訊年級,班級,序號拼接起來組成一個帳號58 account=${username_grade}${username_class}${nu_nn}${i}59 password="$account"60 61 #帳號密碼寫入檔案62 echo 帳號:"$account":密碼:"$password" | tee -a "$accountfile"63 done64 65 #建立帳號密碼66 usernames=$(cat "$accountfile" | cut -d':' -f2)67 68 for u in $usernames69 do70 useradd $u71 echo $u | passwd --stdin $u72 #強制登入修改密碼73 chage -d 0 $u74 75 done76 77 echo "Ok! 建立$nu_amount個賬戶."
如果同一個班的學生有需求在同一個組 將7行改為 useradd -g username_class $u
二.從剛才儲存的檔案大量刪除剛才建立的帳號
手殘建錯了怎麼辦,大量刪除剛才的帳號
1 #!/bin/bash2 # to del the user from file3 4 usernames=$(cat user.passwd | cut -d':' -f2)5 for username in $usernames6 do7 echo "刪除使用者$username"8 userdel -r $username9 done
附上鳥哥書上提供的原版地址http://linux.vbird.org/linux_basic/0410accountmanager/account2.sh
我沒有重複造輪子,我只是在練習。