shell腳本實戰——批次量建立/刪除帳號

前言:該腳本便可批量建立用戶,又可批量刪除用戶,具體針對哪一個用戶進行操做,是在一個文本文件中進行定義的。而且使用此腳本建立的用戶,首次登錄必須修改密碼。vim

[root@localhost ~]# vim create_user.sh 

usergroup=""       #if your account need secondary group,add here
pwmech="openssl"   #"openssl" or "account" is needed.
homeperm="no" # if "yes" then I will modify home dir permission to 711
usepw="123456"               #this is all user init password
# 1.check the accountadd.txt file
action="${1}"        #"create" is useradd and "delete" is userdel
if [ ! -f accountadd.txt ];
        then
          echo "There is no accountadd.txt file,stop here"
        exit 1
fi
[ "${usergroup}" != "" ] && groupadd -r ${usergroup}
rm -f outputpw.txt
usernames=$(cat accountadd.txt)
for username in ${usernames}
do
        case ${action} in
          "create")
             [ "${usergroup}" != "" ] && usegrp=" -G ${usergroup} " || usegrp=""
             useradd ${usegrp} ${username}
             echo ${usepw} | passwd --stdin ${username}   #set password
             chage -d 0 ${username}
             [ "${homeperm}" == "yes" ] && chmod 711 /home/${username}
        echo "username=${username},password=${usepw}" >> outputpw.txt
             ;;
"delete")
               echo "deleting ${username}"
               userdel -r ${username}
               ;;
          *)
              echo "Usage:$0[create | delete]"
               ;;
        esac
done
[root@localhost ~]# cat accountadd.txt            #將須要建立的用戶名寫入該文件
lv1
lv2
lv3
lv4
#進行測試
[root@localhost ~]# sh create_user.sh create              #執行create選項,進行建立
更改用戶 lv1 的密碼 。
passwd:全部的身份驗證令牌已經成功更新。
更改用戶 lv2 的密碼 。
passwd:全部的身份驗證令牌已經成功更新。
更改用戶 lv3 的密碼 。
passwd:全部的身份驗證令牌已經成功更新。
更改用戶 lv4 的密碼 。
passwd:全部的身份驗證令牌已經成功更新。
[root@localhost ~]# tail -n 4 /etc/passwd                         #查看是否建立成功
lv1:x:1004:1005::/home/lv1:/bin/bash
lv2:x:1005:1006::/home/lv2:/bin/bash
lv3:x:1006:1007::/home/lv3:/bin/bash
lv4:x:1007:1008::/home/lv4:/bin/bash
[root@localhost ~]# sh create_user.sh delete                  #執行delete選項,進行刪除
deleting lv1
deleting lv2
deleting lv3
deleting lv4

———————— 本文至此結束,感謝閱讀 ————————bash

相關文章
相關標籤/搜索