1. 程式人生 > >鳥哥的Linux私房菜讀書筆記--centos環境下大量建置賬號的辦法

鳥哥的Linux私房菜讀書筆記--centos環境下大量建置賬號的辦法

1、賬號相關的檢查工具

<1>pwck

[[email protected] hadoop1]# pwck
使用者“ftp”:目錄 /var/ftp 不存在
使用者“gluster”:目錄 /var/run/gluster 不存在
使用者“saslauth”:目錄 /run/saslauthd 不存在
使用者“pulse”:目錄 /var/run/pulse 不存在
使用者“gnome-initial-setup”:目錄 /run/gnome-initial-setup/ 不存在
pwck:無改變

以上賬號大部分為系統賬號,不需要家目錄,所以不存在是正常的錯誤。相應的群組檢查可以使用grpck

<2>pwconv

主要目的:將/etc/passwd內的賬號與密碼移動到/etc/shadow中。

(1)比對/etc/passwd及/etc/shadow,若/etc/passwd記憶體在的賬號並沒有對應的/etc/shadow密碼時,則pwconv會去/etc/logi.defs取用相關的密碼資料,並建立該賬號的/stc/shadow資料

(2)若/etc/passwd記憶體在加密後的資料密碼時,則pwconv會將該密碼欄移動到/etc/shadow內,並將原本/etc/passwd內相對應的密碼欄變成x。一般來說,正常使用useradd增加使用者時,使用pwconv並不會有任何動作,因為/etc/passwd與/etc/shadow並不會有上述兩點問題。

<3>pwunconv

相對於pwconv,pwunconv則是將/etc/shadow內的密碼欄資料寫回/etc/passwd當中,並且刪除/etc/shadow檔案。真的會刪除的,建議儘量不要使用。

<4>chpasswd

讀入未加密前的密碼,並且經過加密後,將加密的密碼寫入到/etc/shadow中,該指令經常被使用在建置大量的賬號的情況。它可以由stdin讀入資料,每筆資料的格式是【username:passwd】

命令:$  echo "使用者名稱:密碼"  | chpasswd

chpasswd會去讀取/etc/login.defs檔案內的加密機制。

2、大量建置賬號模板(適用於passwd --stdin選項)

#!/bin/bash
# This shell script will create amount of linux login accounts for you.
# 1. check the "accountadd.txt" file exist? you must create that file manually.
# one account name one line in the "accountadd.txt" file.
# 2. use openssl to create users password.
# 3. User must change his password in his first login.
# 4. more options check the following url:
# http://linux.vbird.org/linux_basic/0410accountmanager.php#manual_amount
# 2015/07/22 VBird
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
# 0. userinput

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
# 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} # 新增賬號
[ "${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

接下來建立accountadd.txt檔案,在該檔案的每行中輸入一個賬號,其中是否需要修改密碼,是否與賬號相同的資訊,可以自由選擇,若使用openss自動猜密碼時,使用者的密碼請由outputpw.txt去撈

執行上面的指令碼檔案

命令:$  sh accountadd.sh  create