In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (Daniel Falkenberg) wrote:

> Hey all,
> 
> I have a problem here that I don't really know how to go about.
> 
> Basically I want to be able to find a user in the  /etc/passwd with only
> a GID of 45 and a username of what I type the user name to be.
> 
> test5:x:503:503::/home/tunnel:/bin/bash
> test:x:504:45:Test Account:/home/test:/bin/false
> test4:x:506:505:test Account:/home/test4:/bin/false
> test2:x:507:45:Test Account:/home/test2:/bin/false
> daniel:x:508:45:Daniel Merritt:/home/daniel:/bin/false
> 
> As we all know the Unix /etc/passwd file looks like the above...
> 
> Now with the following I want to be able to only find the user name that
> has a GID of 45 and make sure the username exists in /etc/passd in the
> first place.
> 
> #!/usr/bin/perl -w
> 
> $user         = "daneilson";
> $file       = '/etc/passwd';
> 
> open PASSSWD, "$file"  or die "Cannot open $file for reading :$!";
> #Store /etc/passwd as a file
> while ( $lines = <PASSWD>) {
>       #split the /etc/passwd file at every colon and store it as an
> array.
>       @lines = split (/:/, $lines);
> }
> 
> #Now for the fun part...
> #Here I need to be able to search through @lines for the username I
> enter $lines[0]
> #if $user is not found then I need to report an error
> #else if $user is found then I need it to check that it has a GID of 45
> and if it doesn't
> #then I need to report another error.

try this for starters (tested)

#!/usr/bin/perl
require 5.006;
use warnings;
use strict;

my $usrname = $ARGV[0] || 'daneilson';

open(PASSWD, '<', '/etc/passwd') 
    or die "Unable to open /etc/passwd: $!";

#dunno how big it is so let's line-by-line it
my $found = 0;
while (<PASSWD>)
{
    chomp;
    my @line = split /:/;
    if ( (lc($line[0]) eq lc($usrname)) && ($line[3] == 45) )
    {
        ++$found;
        print "Found [$found]:\n\t", join("\n\t", @line), "\n";
    }
}

if ($found)
{
    print "Total records found = [$found]\n";
}
else
{
    print "No records were found that matched\n";
}
__END__
=pod
delete the use warnings; line and use the simple -w switch as in    

    #!/usr/bin/perl -w 

if you don't have 5.6.0 or later on your system, and also change the 
open line to the 2-argument version like so:

    open(PASSWD, '< /etc/passwd') 
        or die "Unable to open /etc/passwd: $!";

you do realise, of course, that you could get similar results with 

    cat /etc/passwd |grep "username" |grep ":45:"

right? 
=cut

The problem with sharks is that they are too large to get to the shallow end of the 
gene pool :P
-- 
Scott R. Godin            | e-mail : [EMAIL PROTECTED]
Laughing Dragon Services  |    web : http://www.webdragon.net/
It is not necessary to cc: me via e-mail unless you mean to speak off-group.
I read these via nntp.perl.org, so as to get the stuff OUT of my mailbox. :-)

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to