Linux - List / Copy group membership for users

12. December 2012 08:00


A quick guide on how to copy group member ship in linux to another user. Which can be useful when setting up new users on a linux machine to make sure that users. It is also a way to find out what groups a user is a member of.


Part 1 - Get a list of groups


To get a list of groups as user is a member of can be done by reading the /etc/group file and doing a little bit of processing. This can be done using the following command.


grep -E "(:|,)<username>(:,|$)" /etc/group|cut -f1 -d:


The complex expression above is built to match specific username in each line of the file. Of which there is 3 different cases ":<username>"  ",<username>,"  ",<username>". So we search for the specific username beginning with a ":" or a "," and also ending in a "," or a "$" which is a newline. Then it cuts on the first field using ":" as a separator.


This will output  a list of group that "<username>" is a member of


Part 2 - Add another user to the same list of groups


Since we know that addgroup can be used to add a user to a group by doing "addgroup <username> <groupname>" then we can expand the above to add a username to each group in the list like this


for i in `grep -E "(:|,)<username>(:,|$)" /etc/group|cut -f1 -d:` ; do

  addgroup <newuser> $i



This will then make sure that the user <newuser> is a member of all the same groups that <username> is.


You should take care using the above as you may give somebody access well beyond what you thought you might have by giving them access to additional groups.


E-mail Kick it! DZone it! Permalink