将用户列表添加到多个组

Rah*_*hul 2 users shell-script group

我想编写一个 shell 脚本,它将在 中定义的用户列表添加users.txt到多个现有组。

例如,我有a, b, c, d, e, f,g用户将根据脚本添加到组中,我有p, q, r, s,t组。以下是/etc/groupsfile的预期输出:

p:x:10029:a,c,d
q:x:10030:b,c,f,g
r:x:10031:a,b,c,e
s:x:10032:c,g
t:x:10033:a,b,c,d,e
Run Code Online (Sandbox Code Playgroud)

那么如何实现呢?

Dan*_*i_l 5

由于没有给出输入示例,我将假设一个非常基本的模式:

Uesrs groups
a p,r,t  
b p,q 
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您有多种选择,因为usermod -G可以本机使用第二列。

就像是

while read line
do
    usermod -G "$(cut -f2 -d" ")" $(cut -f1 -d" ")
done < users.txt
Run Code Online (Sandbox Code Playgroud)

while 循环从users.txt 读取每一行,并将其传递给usermod。
该命令usermod -G group1,group2,group3 user将用户的组更改为请求的组。
cut仅根据 delimiter 分隔字段-d " ",因此第一个字段用作用户名(登录名),第二个字段用于组。如果您希望将组附加到当前(现有)组中 - 添加 -a 使命令看起来像usermod -a -G ...


ter*_*don 5

最好和最简单的方法是使用@DannyG 建议的所需信息解析文件。虽然这是我自己做的方式,但另一种方法是在脚本中对用户/组组合进行硬编码。例如:

#!/usr/bin/env bash

## Set up an indexed array where the user is the key
## and the groups the values.
declare -A groups=(
    ["alice"]="groupA,groupB" 
    ["bob"]="groupA,groupC" 
    ["cathy"]="groupB,groupD"
)

## Now, go through each user (key) of the array,
## create the user and add them to the right groups.
for user in "${!groups[@]}"; do 
    useradd -U -G "${groups[$user]}" "$user" 
done
Run Code Online (Sandbox Code Playgroud)

注意:以上假设 bash 版本 >= 4,因为关联数组在早期版本中不可用。