歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

shel script:學校管理系統批量新建賬號

代碼如下:

1 #!/bin/bash
  2 # History:
  3 #2016/05/05 dairen first release
  4 #2016/05/06 dairen second release
  5 #export LANG=zh_TW.big5
  6 export PATH=/sbin:/usr/sbin:/bin:/usr/bin
  7 accountfile="user.passwd"
  8 # 1. 進行賬號相關的輸入先!
  9 read -p "賬號開頭代碼 ( Input title name, ex> std )======> " username_start
 10 read -p "賬號層級或年級 ( Input degree, ex> 1 or enter )=> " username_degree
 11 read -p "號碼部分的數字位數 ( Input \# of digital )======> " nu_nu
 12 read -p "起始號碼 ( Input start number, ex> 520 )========> " nu_start
 13 read -p "賬號數量 ( Input amount of users, ex> 100 )=====> " nu_amount
 14 read -p "口令標准 1) 與賬號相同 2)隨機數自定義 ==============> " pwm
 15 if [ "$username_start" == "" ]; then
 16         echo "沒有輸入開頭的代碼" ; exit 1
 17 fi
 18 # 判斷數字系統
 19 testing0=$(echo $nu_nu     | grep '[^0-9]' )
 20 testing1=$(echo $nu_amount | grep '[^0-9]' )
 21 testing2=$(echo $nu_start  | grep '[^0-9]' )
 22 if [ "$testing0" != "" -o "$testing1" != "" -o "$testing2" != "" ]; then
 23         echo "輸入的號碼不對啦!有非為數字的內容!" ; exit 1
 24 fi
 25 if [ "$pwm" != "1" ]; then
 26         pwm="2"
 27 fi
 28 
 29 # 2. 開始輸出賬號與口令文件!
 30 [ -f "$accountfile" ] && mv $accountfile "$accountfile"$(date +%Y%m%d)#文件若已存在就重命名
 31 nu_end=$(($nu_start+$nu_amount-1))
 32 for (( i=$nu_start; i<=$nu_end; i++ ))
 33 do
 34         nu_len=${#i}#取得字符串長度
<pre name="code" class="html"> 35         if [ $nu_nu -lt $nu_len ]; then
 36                 echo "數值的位數($i->$nu_len)已經比你配置的位數($nu_nu)還大!"
 37                 echo "程序無法繼續"
 38                 exit 1
 39         fi
 40         nu_diff=$(( $nu_nu - $nu_len ))
 41         if [ "$nu_diff" != "0" ]; then
 42                 nu_nn=0000000000
 43                 nu_nn=${nu_nn:1:$nu_diff}#對nu_nn從1位開始截取nu_diff位
 44         fi
 45         account=${username_start}${username_degree}${nu_nn}${i}
 46         if [ "$pwm" == "1" ]; then
 47                 password="$account"
 48         else
 49                 password=$(openssl rand -base64 6)#用openssl庫產生偽隨機數
 50         fi
 51         echo "$account":"$password" | tee -a "$accountfile"#輸出到文件
 52 done
 53 
 54 # 3. 開始創建賬號與口令!
 55 cat "$accountfile" | cut -d':' -f1 | xargs -n 1 useradd -m  #add account
 56 chpasswd < "$accountfile"   #add password
 57 pwconv                         #將密碼從/etc/passwd到/etc/shadow
 58 echo "OK!創建完成!"

Copyright © Linux教程網 All Rights Reserved