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>
- !/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) );
print "no user specified\n";
exit 1;}
else {
$user = $ARGV[0];
}
- get list of current extended groups for user
my @current_groups = split(/ /, `groups $user` );
chomp(@current_groups);
- slice of extended groups only
@current_groups = @current_groups[3 .. $#current_groups];
my @groups = ( @current_groups, @add_groups );
- remove duplicate entries
my %temp= ();
@groups = grep ++$temp{$_} < 2, @groups;
- remove items that are in rm_groups
@temp{@groups} = ();
foreach (@rm_groups) {
delete $temp{$_};}
@groups = sort keys %temp;
my $arg = join (',',@groups);
- call usermod
print "executing usermod -G '$arg' $user\n";
system("usermod -G '$arg' $user");
Post new comment