如何從文字檔案中的資料新增用戶

如何從文字檔案中的資料新增用戶

我有一個關於在 Linux 中建立多個使用者的問題,但我需要一個程式來處理它。新建一個users.txt文件,內容如下:

adams:5000:Adams, John Couch:/bin/bash
atiyah:5001:Atiyah, Michael:/bin/csh
babbage:5002:Babbage, Charles:/bin/csh
baker:5003:Baker, Alan:/bin/csh
barrow:5004:Barrow, Isaac:/bin/bash

……(文件中有70個使用者名稱)

我想知道如何編寫腳本來自動添加這些用戶。

答案1

假設您的檔案名稱為file.該腳本將完成以下工作:

USERNAME=$(cat file | cut -d: -f1)
echo "$USERNAME"

ID=$(cat file | cut -d: -f2)
echo "$ID"

USER_SHELL=$(cat file | cut -d, -f2 | cut -d: -f2)
echo "$USER_SHELL"

useradd -m -s "$USER_SHELL" -u "$ID" "$USERNAME"

答案2

這是完成工作的最低限度的腳本。它確保用戶名和 uid 都未被使用。它為每個使用者建立一個符合的群組(使用 gid=uid) - 它不會檢查 gid 或群組名稱是否已經存在(留給讀者練習 - 提示: use getent group)。

注意:下面的腳本未經測試,但我之前已經編寫過類似的腳本一百萬次(稍微誇張)......可能有一些小錯誤需要修復。

#! /bin/bash
# get newusers file from first arg on cmd line or default to 'newusers.txt'
nf="${1:-newusers.txt}"

# get existing usernames and uids.
names="^($(getent passwd | cut -d: -f1 | paste -sd'|'))$"
 uids="^($(getent passwd | cut -d: -f3 | paste -sd'|'))$"

yesterday=$(date -d yesterday +%Y-%m-%d)
# temp file for passwords
tf=$(mktemp) ; chmod 600 "$tf"

while IFS=: read u uid gecos shell; do
    gid="$uid" ; homedir="/home/$u"
  
    useradd  -e "$yesterday" -m -d "$homedir" -c "$gecos" \
             -u "$uid" -g "$gid" -s "$shell" "$u"

    groupadd -g "$gid" "$u"
  
    # generate a random password for each user..
    p=$(makepasswd)
    echo "$u:$p" >> "$tf"
done < <(awk -F: '$1 !~ names && $2 !~ uids' names="$names" uids="$uids" "$nf")

# uncomment to warn about users not created:
#echo Users not created because the username or uid already existed: >&2
#awk -F: '$1 ~ names || $2 ~ uids' names="$names" uids="$uids" "$nf" >&2    

# uncomment the cat to display the passwords in the terminal
echo ; echo "passwords are saved in $tf"
# cat "$tf"

# set passwords using `chpasswd:
chpasswd < "$tf"

如果未安裝,請使用pwgenmakepassword或任何類似程序。makepasswd或編寫您自己的連接4 個以上隨機5 個以上字母的單詞,以獲得一個易於記住的密碼,長度至少為20 個字符- 將一些單詞大寫並在每個單詞之間插入隨機的1-3位數字和/或標點符號以使密碼均勻更長並增加暴力搜尋空間。隨機密碼產生已經被重新發明了很多次。

您可以列印使用者名稱和密碼(來自"$tf")並將它們切成條狀(在每條之間保留一些空白行user:password)以提供給每個使用者。告訴他們立即更改密碼並銷毀紙條。密碼設定為過期"$yesterday"(需要 GNU date),因此使用者第一次登入 shell 時應提示其變更密碼。

答案3

有一種更簡單的方法可以在批次模式下從檔案新增或更新使用者:命令newusers(8),該命令由陰影工具開關。該工具套件至少應作為 Debian 及其衍生版本的軟體包提供。它在我正在使用的 Arch Linux 中可用。

有關如何使用它的信息,請參閱man newusers

相關內容