hotshot has asked for the wisdom of the Perl Monks concerning the following question:

Hi Guys

Is there a way to tell the getpwxxx functions to search only in the local /etc/passwd ?
If no such thing is possible, is there a way to do it without searching this file by myself?

Thanks

Hotshot

Replies are listed 'Best First'.
Re: getpwXXX
by virtualsue (Vicar) on Feb 20, 2002 at 13:46 UTC
    If you want to be certain that your script only searches a local /etc/passwd file, you'll have to do it yourself. On the bright side, it's not hard to do that:
    open FH, '/etc/passwd' or die "Can't open /etc/passwd, $!"; my @matches = grep { chomp; /thing_to_match/ } <FH>;
    or you can iterate through the file & split out each line like so:
    while (<FH>) { chomp; my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = split /:/; }
    The following code mimics getpwnam:
    sub my_getpwnam { my $name_m = shift; open FH, '/etc/passwd' or die "Can't open /etc/passwd, $!"; my @match = grep { chomp; /^$name_m:/ } <FH>; if (!@match) { return (); } # return empty list if not found return split /:/, $match[0]; }
    If you really don't want to do it yourself, tilly's Text::xSV module could be your answer.

    Update: Added a missing brace & stuck in an error check

Re: getpwXXX
by derby (Abbot) on Feb 20, 2002 at 14:32 UTC
    hotshot,

    or have some fun with the c function fgetpwent and INLINE

    #!/usr/local/bin/perl -w use Inline C; use Data::Dumper; @ARGV || die "usage $0 <filename>\n"; $entries = getmypwent($ARGV[0]); print Dumper( $entries ); __END__ __C__ #include <pwd.h> #include <stdio.h> #include <sys/types.h> SV *getmypwent( char *filename ) { FILE *ih; struct passwd *p; int len; AV *array; HV *hash = newHV(); if( ( ih = fopen( filename, "r" ) ) != NULL ) { while( p = fgetpwent( ih ) ) { hv_store(hash, p->pw_name, strlen(p->pw_name), newRV_noinc((SV*)array = newAV()), 0); av_push(array, newSVpvf("%s", p->pw_passwd)); av_push(array, newSVpvf("%d", p->pw_uid)); av_push(array, newSVpvf("%d", p->pw_gid)); av_push(array, newSVpvf("%s", p->pw_gecos)); av_push(array, newSVpvf("%s", p->pw_dir)); av_push(array, newSVpvf("%s", p->pw_shell)); } fclose(ih); } return newRV_noinc((SV*) hash); }

    -derby

Re: getpwXXX
by gellyfish (Monsignor) on Feb 20, 2002 at 13:10 UTC

    This is as system configuration rather than a Perl question - you will need to change the appropriate entry in /etc/nsswitch.conf (or whatever its equivalent is on your machine) so that it only looks in the files rather than going to NIS or whatever

    /J\

Re: getpwXXX
by traveler (Parson) on Feb 20, 2002 at 16:30 UTC
    Check CPAN. There are modules to do that.

    HTH, --traveler