Chad Perrin wrote:
On Mon, Dec 18, 2006 at 04:50:57PM -0700, Tom Smith wrote:
I need to capture a user's group memberships for further processing in a Perl script. The user's username is passed to the script via the command line and captured with ARGV. From there, I want to determine the group memberships (much like executing `groups` from the command line) and run those through a loop for processing.

I seem to be having a problem locating a function that will do this. I've looked at several and tried a couple, but either I'm doing something wrong or I'm using the wrong functions. All of the ones I've tried are part of getgr*.

I'm very new to Perl so maybe I'm just looking for the wrong terms or something. I've googled and searched perldoc.perl.org.

Can anyone offer any suggestions or point me in the right direction?

Thanks, in advance, for your help!

A simple solution that comes immediately to mind is to iteratively check
for the user's name in lines of the /etc/group file, and grab the first
field (before the first colon) of each line that matches.  This'll give
you a list of groups.  There are likely other, more elegant solutions to
the problem, but that's the first that springs to mind.

It'd require some regex use for matching, and either a regex or split()
to separate the first field.  It should be extremely simple to write
with only basic understanding of the language and very simple
understanding of Perl regex syntax, but I'm not providing code so that I
don't just do your work for you.  Let us know if you have any problems
with the concepts.

relevant perldocs:
  perldoc perlre
  perldoc -f split
  perldoc perlintro

Thank Chad (and John) for your input on this. I thought I'd post the portion of the script that I was trying to work out to see if there's room for improvement. This should work on any *nix system. The format of the command is simple: `test.pl username`, where username is a real username on the system in question. Here's the script:

test.pl:
#!/usr/bin/env perl

use strict;
use warnings;

# Determine which Linux groups the user belongs to.
open(FILE,'</etc/group') or die "Can't open /etc/group.";

my @memberof;
while ($_ = <FILE>) {
       if($_ =~ /$ARGV[0]/) {
               my @groups = split(/:/,$_);
               push(@memberof,$groups[0]);
       }
}

close FILE;

print "[EMAIL PROTECTED]";


So is there a better way to do this, or perhaps a cleaner way?


Thanks again for your help!

~ Tom

Reply via email to