前言:
學習或生產工作中,你可能遇到批量創建 Centos 用戶的情況,一段shell 腳本來幫助你:
如何做:
0,我們把腳本保存為 ac.sh;
1,提前建立一個 accountadd.txt 的文本,一行一個寫入需要建立的用戶名;
2,使用 # ./ac.sh create 來執行批量創建;
3,密碼會存入當前目錄的 outputpw.txt;
4,使用 # ./ac.sh delete 來執行批量刪除;
腳本:
# 0. 這個shell 會為你批量建立 user 賬號;
# 1. 檢查 "accountadd.txt" 是否存在? 你需要先手工建立這個文本;
# 2. "accountadd.txt" 中一個用戶名一行;
# 3. 使用 openssl 創建 users password;
# 4. 設定新用戶初次登錄必須修改密碼;
# 0. userinput
usergroup="" # 需要建立新組,在這裡添加;
pwmech="openssl"
homeperm="no" # if "yes" then it will modify home dir permission to 711
# 1. check the accountadd.txt file
action="${1}" # 命令動作,建立用戶使用"create",刪除用戶使用 "delete" ;
if [ ! -f accountadd.txt ]; then
echo "沒有 accountadd.txt 文件!"
exit 1
fi
# 2. 執行
[ "${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} # 新增賬號;
[ "${pwmech}" == "openssl" ] && usepw=$(openssl rand -base64 6) || usepw=${username}
echo ${usepw} | passwd --stdin ${username} # 創建密碼;
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
執行創建:
# ./ac.sh create
查看密碼:
# cat outputpw.txt
批量刪除:
# ./ac.sh delete
代碼高亮截圖:
還要注意:
如果你在windows下複製粘貼編輯腳本代碼,
若出現異常情況,請把 windows 換行符\r\n 替換成 linux 換行符:
以上面的腳本舉例,執行下面代碼轉換換行符:
# sed -i 's/\r//' ac.sh
- window下默認是 \r\n
- linux下是\n
- unix下是\r
人的生命是有限的,只有知識永存!
閱讀更多 你永遠得不到的小老弟 的文章