Linux - List / Show Users Thats Belongs Corresponding Groups

January 28, 2013 | By
| Reply More

Usually, when we talk of listing member of any unix group, let’s say, linux, then it really gets a bit complicated, there are number of ways to get the group members details as below

1. cat /etc/group
2. id [user_name]
3. getent group [group_name]

All such output will only provide group info of associated identity and will produce in “not so straight” way unless you have some LDAP kind of services in your system, also we may be missing other kinds of users added for NIS,LDAP etc.

There should be a way to get the list as visible to the PAM of the system, so we can have a little script here that helps us and gives us proper solution for listing all members in all groups present on a particular system.

A simple perl script below,

#!/usr/bin/perl -T
#
# Lists members of all groups, or optionally just the group
# specified on the command line.
use strict; use warnings;

$ENV{"PATH"} = "/usr/bin:/bin";

my $wantedgroup = shift;

my %groupmembers;
my $usertext = `getent passwd`;

my @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;

foreach my $userid (@users)
{
my $usergrouptext = `id -Gn $userid`;
my @grouplist = split(' ',$usergrouptext);

foreach my $group (@grouplist)
{
$groupmembers{$group}->{$userid} = 1;
}
}

if($wantedgroup)
{
print_group_members($wantedgroup);
}
else
{
foreach my $group (sort keys %groupmembers)
{
print "Group ",$group," has the following members:\n";
print_group_members($group);
print "\n";
}
}

sub print_group_members
{
my ($group) = @_;
return unless $group;

foreach my $member (sort keys %{$groupmembers{$group}})
{
print $member,"\n";
}
}

Output of above script.

[root@db0 ~]# ./userlist.pl
Group adm has the following members:
adm
daemon
root

Group audio has the following members:
gdm

Group avahi has the following members:
avahi

Group avahi-autoipd has the following members:
avahi-autoipd

Group bin has the following members:
bin
daemon
root

Group daemon has the following members:
bin
daemon
root

Group dbus has the following members:
dbus

Group disk has the following members:
root

Group ftp has the following members:
ftp

Group gdm has the following members:
gdm

Group gopher has the following members:
gopher

----Output Truncated---

So this script made our life easier, and can be a good utility to be used for any such future queries and on any unix system.

Filed Under : LINUX COMMANDS, LINUX HOWTO, USER MANAGEMENT

Tagged With :

Free Linux Ebook to Download

Leave a Reply

Commenting Policy:
Promotion of your products ? Comment gets deleted.
All comments are subject to moderation.