Advertisement
Tritonio

How to list all users in a Linux group?

Mar 15th, 2021
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1.  
  2.  
  3. Unfortunately, there is no good, portable way to do this that I know of. If you attempt to parse /etc/group, as others are suggesting, you will miss users who have that group as their primary group and anyone who has been added to that group via a mechanism other than UNIX flat files (i.e. LDAP, NIS, pam-pgsql, etc.).
  4.  
  5. If I absolutely had to do this myself, I'd probably do it in reverse: use id to get the groups of every user on the system (which will pull all sources visible to NSS), and use Perl or something similar to maintain a hash table for each group discovered noting the membership of that user.
  6.  
  7. Edit: Of course, this leaves you with a similar problem: how to get a list of every user on the system. Since my location uses only flat files and LDAP, I can just get a list from both locations, but that may or may not be true for your environment.
  8.  
  9. Edit 2: Someone in passing reminded me that getent passwd will return a list of all users on the system including ones from LDAP/NIS/etc., but getent group still will still miss users that are members only via the default group entry, so that inspired me to write this quick hack.
  10.  
  11.  
  12. #!/usr/bin/perl -T
  13. #
  14. # Lists members of all groups, or optionally just the group
  15. # specified on the command line
  16. #
  17. # Copyright © 2010-2013 by Zed Pobre (zed@debian.org or zed@resonant.org)
  18. #
  19. # Permission to use, copy, modify, and/or distribute this software for any
  20. # purpose with or without fee is hereby granted, provided that the above
  21. # copyright notice and this permission notice appear in all copies.
  22. #
  23.  
  24. use strict; use warnings;
  25.  
  26. $ENV{"PATH"} = "/usr/bin:/bin";
  27.  
  28. my $wantedgroup = shift;
  29.  
  30. my %groupmembers;
  31. my $usertext = `getent passwd`;
  32.  
  33. my @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;
  34.  
  35. foreach my $userid (@users)
  36. {
  37. my $usergrouptext = `id -Gn $userid`;
  38. my @grouplist = split(' ',$usergrouptext);
  39.  
  40. foreach my $group (@grouplist)
  41. {
  42. $groupmembers{$group}->{$userid} = 1;
  43. }
  44. }
  45.  
  46. if($wantedgroup)
  47. {
  48. print_group_members($wantedgroup);
  49. }
  50. else
  51. {
  52. foreach my $group (sort keys %groupmembers)
  53. {
  54. print "Group ",$group," has the following members:\n";
  55. print_group_members($group);
  56. print "\n";
  57. }
  58. }
  59.  
  60. sub print_group_members
  61. {
  62. my ($group) = @_;
  63. return unless $group;
  64.  
  65. foreach my $member (sort keys %{$groupmembers{$group}})
  66. {
  67. print $member,"\n";
  68. }
  69. }
  70.  
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement