여러 그룹에 사용자 목록 추가

여러 그룹에 사용자 목록 추가

users.txt여러 기존 그룹에 정의된 사용자 목록을 추가하는 쉘 스크립트를 작성하고 싶습니다 .

예를 들어 스크립트를 기반으로 그룹에 추가될 , , a, b, c, d, e사용자가 있고 , 그룹 이 , , , , 있습니다. 다음은 파일의 예상 출력입니다 .fgpqrst/etc/groups

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

그렇다면 이것을 달성하는 방법은 무엇입니까?

답변1

가장 좋고 쉬운 방법은 필요한 정보가 포함된 파일을 다음과 같이 구문 분석하는 것입니다.@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

노트:위의 내용은 이전 버전에서는 연관 배열을 사용할 수 없으므로 bash 버전 >= 4를 가정합니다.

답변2

입력 예제가 제공되지 않으므로 매우 기본적인 패턴을 가정하겠습니다.

Uesrs groups
a p,r,t  
b p,q 

이 경우 usermod -G두 번째 열을 기본적으로 사용할 수 있으므로 여러 가지 옵션이 있습니다.

그것은 마치

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

while 루프는 users.txt에서 각 줄을 읽고 이를 usermod에 전달합니다.
이 명령은 usermod -G group1,group2,group3 user사용자의 그룹을 요청된 그룹으로 변경합니다.
cut필드는 구분 기호로만 구분되므로 -d " "첫 번째 필드는 사용자 이름(로그인)으로 사용되고 두 번째 필드는 그룹에 사용됩니다. 현재(기존) 그룹에 그룹을 추가하려면 -a를 추가하여 명령이 다음과 같이 되도록 하십시오.usermod -a -G ...

답변3

귀하의 의견을 바탕으로 스크립트를 정적으로 작성하고 그 안에 그룹을 직접 작성할 수 있습니다. 스크립트는 표준 입력의 사용자 목록(한 줄에 한 명씩)을 예상합니다. 예를 들어 ./script < users.txt호출하십시오.

#!/bin/bash

groups="p q r" # the list of all groups you want your users in

# the following function is a case statement
# it takes as first argument a user, and as second argument a group
# it returns 0 if the user must be added to the group and 1 otherwise
must_belong_to() {
     case $2 in  # first we explore all the groups
     p)
          case $1 in  # and for each of them, we examine the users
          a | b )  # first selection: the users that must belong to the group
              true
          ;;
          *) # second selection: all the others
              false
          ;;
          esac
      q)
          # same here...
          ;;
      esac
  }

# we loop on the input file, to process one entry 
# (i.e. one user) at a time
while read user
do
    # We add the user. You may want to give some options here 
    # like home directory (-d), password (-p)...
    useradd $user 

    # then we loop on the existing groups to see in which 
    # one the user must be added
    for g in $groups  
    do
        # if the user must be added to the group $g
        if must_belong_to $user $g  
        then
             # we add it with the command gpasswd
             gpasswd -a $user $g 
        fi
    done
 done

@terdon이 설명했듯이 이 버전은 must_belong_to() 빠르게 성장할 수 있습니다. 연관 배열을 사용하는 또 다른 솔루션은 다음과 같습니다.

#!/bin/bash
declare -A groups

# we declare all the groups and then, for each one, its members
all_the_groups="a b"
groups[a]="p q r"
groups[b]="q r s"

must_belong_to() {
    # we extract a list of all users for the group in parameter
    read -a all_the_users <<< "${groups["$2"]}"

    # we iterate over the users from the group
    for u in $all_the_users
    do
        # if the user belong to the group, 
        # we return here
        [[ $u == $1 ]] && return 0
    done

    # in case the user dosn't belong to the group,
    # we end up here
    return 1
}

관련 정보