テキスト ファイルのデータからユーザーを追加する方法

テキスト ファイルのデータからユーザーを追加する方法

Linux で複数のユーザーを作成する方法について質問がありますが、それを実行するプログラムが必要です。新しいユーザーの 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 またはグループ名がすでに存在するかどうかはチェックしません (読者の練習問題として残しておきます - ヒント: を使用してください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"

pwgenまたはmakepassword、または同様のプログラムがインストールされていない場合は、それを使用してくださいmakepasswd。または、4 文字以上のランダムな 5 文字以上の単語を連結して、少なくとも 20 文字の覚えやすいパスワードを作成する独自のパスワードを作成します。一部の単語を大文字にし、各単語の間にランダムな 1 ~ 3 桁の数字や句読点を挿入して、パスワードをさらに長くし、ブルート フォース検索空間を拡大します。ランダム パスワード生成は、何度も再発明されてきました。

ユーザー名とパスワードを ( から) 印刷し"$tf"、それを細長く切って (各 の間に数行の空白行を残すuser:password)、各ユーザーに渡すことができます。ユーザーにパスワードをすぐに変更し、その細長い紙を破棄するように伝えます。パスワードには有効期限が設定されているため"$yesterday"(GNU が必要date)、ユーザーが初めてシェルにログインするときにパスワードを変更するように求めるプロンプトが表示されます。

答え3

バッチモードでファイルからユーザーを追加または更新するより簡単な方法がありますnewusers(8)ツール スイート。このツール スイートは、少なくとも Debian とその派生ディストリビューションのパッケージとして利用できるはずです。私が使用している Arch Linux では利用できます。

使用方法については、man newusers

関連情報