adding list of users to multiple groups

4,897

Solution 1

The best and simplest approach would be to parse a file with the required information as suggested by @DannyG. While that's the way I would do it myself, another would be to hardcode the user/groups combinations in your script. For example:

#!/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

NOTE: The above assumes a bash version >= 4 since associative arrays were not available in earlier versions.

Solution 2

Since no input example is given, I'm going to assume a very basic patern:

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

In that case you have several options, because usermod -G can use the second column natively.

something like

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

The while loop reads each line from users.txt, and passes it to usermod.
the command usermod -G group1,group2,group3 user changes the user's groups to the requested groups.
cut merely separates the fields based on delimiter -d " ", so first field is used as username (login name) and 2nd field is for the groups. I f you wish to append the groups to current (existing) groups - add -a so the command looks like usermod -a -G ...

Solution 3

Given your comments, you can just statically build the script with the groups hard-written in it. This script expect a list of users, one user per line, on the standard input. So call it with ./script < users.txt for example.

#!/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

As explained by @terdon, this version of must_belong_to() can grow big quickly. Here is another solution using associative arrays:

#!/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
}
Share:
4,897

Related videos on Youtube

maestar
Author by

maestar

Updated on September 18, 2022

Comments

  • maestar
    maestar over 1 year

    Whenever I try this,

    $conn = mysqli_connect(example.com,user,password,database);
    

    I don't know what I'm doing wrong. My php version is php 5.3.above. Why is this code not working in a live website. Its fine in localhost.

    • Dave
      Dave over 11 years
      is mysqli installed/enabled in the php?
    • hjpotter92
      hjpotter92 over 11 years
      Also, try it with the port number.
    • deceze
      deceze over 11 years
      Define "not working". What happens or doesn't happen?
    • maestar
      maestar over 11 years
      I tried both, mysql/mysqli
    • 0xmtn
      0xmtn over 11 years
      Can you please use mysqli_error() to get the error?
    • Ben Carey
      Ben Carey over 11 years
      Whilst this does not answer your question, may I advise you to start using PDO or MySQLi. The mysql_* functions are now deprecated, therefore writing applications with them is not a great idea. See here for more info: php.net/manual/en/book.mysqli.php
    • maestar
      maestar over 11 years
      Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'example-host.com' (using password: YES) in /home/morecamb/public_html/includes/config.php on line 26 Could not connect: Access denied for user 'user'@'example-host.com' (using password: YES) . This is the error i get. This happened when i tried mysql instead of mysqli
    • John Conde
      John Conde over 11 years
      Sounds like a bad username and/or password
    • Ben Carey
      Ben Carey over 11 years
      @subash90 The clue is in the error!!! You are using the wrong username or password!
    • Michael Berkowski
      Michael Berkowski over 11 years
      ... or the user has a GRANT with that password, but not from the host you are connecting via.
    • maestar
      maestar over 11 years
      I'm pretty much sure about using the username or password, cause i copied and pasted that
    • Daryl Gill
      Daryl Gill over 11 years
      @BenCarey there is a request being made using MySQLI not MYSQL
    • maestar
      maestar over 11 years
      I'm still trying. What should be the values of hostname,username,password or other thing in live site? Suppose my site is example.com. Are there any rules? I'm using cpanel.
    • Dave
      Dave over 11 years
      chances are your db server is running on localhost so change the DB_HOST define to localhost. Also check you've setup a user correctly and flushed the privlidges of the mysql server to commit the user changes
    • maestar
      maestar over 11 years
      I'm getting this now. Fatal error: Call to undefined function mysqli_connect()
    • Rahul
      Rahul almost 10 years
      @lgeorget: It will be fixed. I mean for particular group, users will be predefined. say group p will always have users a, b, f likewise other groups too would have some users.
    • lgeorget
      lgeorget almost 10 years
      There are several answers for your questionsyet. The main difference (in my opinion) is whether you specify for each group the users it includes, or for each user, the groups it belongs to.
  • crush
    crush over 11 years
    Explain not working. Did you test that the $conn was not false?
  • maestar
    maestar over 11 years
    I get this Fatal error: Call to undefined function mysqli_connect()
  • Tjoene
    Tjoene over 11 years
    Are you sure that mysqli is enabled in php? Check if it listed in the phpinfo();
  • maestar
    maestar over 11 years
    Its solved now. Thank you for your attention
  • Rahul
    Rahul almost 10 years
    can you please elaborate this ? As I have mentioned I'm new to shell script.
  • lgeorget
    lgeorget almost 10 years
    @arzyfex Sure, I commented my script. Is it more clear?
  • Rahul
    Rahul almost 10 years
    @Dani_I: Thank you for your suggestion.. It helped me in another scripts as well.