Automatically add and remove groups to a user

Tagged:  

So I wanted to write a shell script to add groups to users. I found out that usermod can only set all group memberships at once, there is no way to simply add one group at a time.

I wrote a perl script to do what I want. Just call it with -a 'group' to add a group to a user and -d 'group' to remove a group. You can comma seperate multiple groups or use multiple switches on the command line. Of course you have to be root.

Note that this script makes assumptions about the output of the groups command. It expects groups to output like "user : initialgroup extended1 extended2"

Maybe I will clean it up one day to not use the groups command and do more sanity checks. Right now it relies on usermod to check that users and groups exist.

<code syntax=perl>

  1. !/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;

my @add_groups;
my @rm_groups;
my $user;

my $result = GetOptions (

 "add=s" => \@add_groups,
 "remove|delete=s" => \@rm_groups,

);

@add_groups = split( /,/, join(',',@add_groups) );
@rm_groups = split( /,/, join(',',@rm_groups) );

if ( ! $ARGV[0] ) {
    print "no user specified\n";    
    exit 1;

}

else {

    $user = $ARGV[0];

}

  1. get list of current extended groups for user

my @current_groups = split(/ /, `groups $user` );
chomp(@current_groups);

  1. slice of extended groups only

@current_groups = @current_groups[3 .. $#current_groups];

my @groups = ( @current_groups, @add_groups );

  1. remove duplicate entries

my %temp= ();
@groups = grep ++$temp{$_} < 2, @groups;

  1. remove items that are in rm_groups
%temp = ();
@temp{@groups} = ();
foreach (@rm_groups) {
   delete $temp{$_};

}

@groups = sort keys %temp;

my $arg = join (',',@groups);

  1. call usermod

print "executing usermod -G '$arg' $user\n";
system("usermod -G '$arg' $user");

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is to verify that you are a human.