>>>>> "Matija" == Matija Papec <[EMAIL PROTECTED]> writes:

Matija> is there a more elegant way to find out who is running a
Matija> script? %ENV is not reliable and it doesn't contain USER when
Matija> booting the system, and "whoami" is external command(yuck :) )
Matija> tnx!

To clarify and summarize the other answers given in this thread:

scalar getpwuid($<) is unspoofable and reliable, and returns a username.
However, if multiple users have the same uid (rare these days), you
might not get the one that the user actually used for login.

getlogin() returns the user that has most recently logged in on the
process's "controlling tty".  It's unspoofable, but it's possible that
it's wrong, especially for background processes.  However, it *would*
distinguish between multiple names for the same user uid.

$ENV{USER} (or $ENV{LOGNAME} in SysV environments) was originally set
to the getlogin() value at login, but of course can be trivially
manipulated by the user.

One strategy I've taken in the past is something like this:

    sub whoami {
      for ($ENV{USER}, $ENV{LOGNAME}, getlogin()) {
        if (getpwnam($_) == $<) {  ## is this a matching uid?
          return $_;  ## return that name
        }
      }
      return scalar getpwuid($<); ## fallback, return name for this uid
    }

This correctly handles multiple logins for the same uid, at the risk
of being coercible to the wrong login with no change of privilege, and
is the quickest for the common case (classic $ENV{USER} is correct).

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<[EMAIL PROTECTED]> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!

Reply via email to