2010年9月14日 星期二

建立帳號script

1,建立文字檔(包含帳號密碼資訊)
$vim users.txt
a001:a001
a002:a002
a003:a003
        :

修正版:(互動式自動產生帳號流水號)
#!/bin/bash
#自動產生帳號,密碼與帳號一致

while [ -z "$filename" ]
do
   echo ""
   read -p  "請輸入要建立的檔案名稱: " filename
   if [ "${filename##*.}" != "txt" ]
   then
      echo "僅能接受txt文字檔格式"
      unset filename
   fi
done

if [ -f "$filename" ]
then
   read -p "該檔案已存在,是否要刪除(default: no)? " ans
   if [ "$ans" == "Y" ]||[ "$ans" == "y" ]
   then
      rm $filename
   else
      unset filename
      while [ -z "$filename" ]
      do
         echo ""
         read -p  "另一個名稱: " filename
         if [ "${filename##*.}" != "txt" ]
         then
             echo "僅能接受txt文字檔格式"
         unset filename
         fi
      done
   fi
fi

while [ -z "$num" ]
do
   echo ""
   read -p "請輸入要產生的帳號數量: " num

   s=$(echo $num|tr -d "0-9")
   if [ -n "$s" ]||[ "$num" -le "0" ]
   then
      echo "請輸入合法且大於零的數字"
      unset num
   fi
done

while [ -z "$name" ]
do
   echo ""
   read -p "請輸入要產生的帳號名稱: " name

   n=$(echo $name|tr -d "a-z" |tr -d "A-Z")
   if [ -n "$n" ]
   then
      echo ""
      echo "帳號名稱不可使用特殊字元或數字"
      unset name
   fi
done

touch $filename
count=1
if [ "$num" -lt 10 ]
then
   while [ "$count" -le "$num" ]
   do
      echo -e $name"0"$count:$name"0"$count >> $filename
      count=$(($count+1))

   done
else
   while [ "$count" -lt 10 ]
   do
      echo -e $name"0"$count:$name"0"$count >> $filename
      count=$(($count+1))
   done
   while [ "$count" -le "$num" ]
   do
      echo -e "$name$count:$name$count" >> $filename
      count=$(($count+1))
   done
fi


2.建立批次程式:
$vim makeuser.sh
#!/bin/bash
#Author : Marcus Tsai  20100914
#檔案固定,判斷是否由root執行,判斷檔案是否存在
filename=/home/student/bin/users.txt
[ "$USER" != "root" ] && echo "need root permision" && exit 1
[ ! -f "$filename" ] && echo "file not found" && exit 1
s=$(cat $filename)

for us in $s
do
        uname="${us%%:*}"
        passwd="${us##*:}"

        useradd -m -s /bin/bash $uname
        echo "$uname:$passwd" |chpasswd

done

exit 0

<1>程式修正版:
#修改成由使用者自帶檔案位置
#!/bin/bash
#Author : Marcus Tsai  20100914
#filename=/home/student/bin/users.txt

#判斷是否root執行,參數是否沒給或超過1個,判斷檔案是否存在
[ "$USER" != "root" ] && echo "need root permision" && exit 1
[ "$#" != "1" ] && echo "wrong parameter!!just one please. " && exit 1
[ ! -f "$1" ] && echo "file not found" && exit 1

s=$(cat $1)

for us in $s
do
        uname="${us%%:*}"
        passwd="${us##*:}"

        useradd -m -s /bin/bash $uname
        echo "$uname:$passwd" |chpasswd

done

exit 0

沒有留言:

張貼留言