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

I'm writing something where I need to get the user id (or username - either way I can eventually use the getpw* functions) of the user who actually logged in. The problem is that the script in question is run as root - but not setuid (for various reasons). So users login as themselves, then "su" to root.

The solution I was using was to just check $ENV{LOGNAME}. However it seems this isn't set to the logged in user when the user types "su -" instead of plain old "su".

I know this can be done, because /usr/bin/ftp does it (when you ftp to some site, it still gives you the option of using the username you logged in as for the remote username). Does ftp just traverse up the process tree until it finds a process not owned by root, or ultimately finds init?

Any help to solve this greatly appreciated.

Replies are listed 'Best First'.
Re: How to get the logged in user id
by Zaxo (Archbishop) on May 29, 2002 at 13:42 UTC

    I believe you want getlogin. It worked for me on linux under both forms of su.

    Camel 3 suggests my $login = getlogin() || getpwuid() || "Intruder!";

    After Compline,
    Zaxo

Re: How to get the logged in user id
by jeffenstein (Hermit) on May 29, 2002 at 14:10 UTC

    You may need to resort to using `tty` and the output of `who`. This will (normally) show who logged into the tty, and won't be affected by su.

      Actually this is what I resorted to doing. The code already had getlogin() in it, but it was still returning root. I have no idea why, so I just used `tty` and `who | grep '$tty' | cut -d" " -f1`. Seems to work like a charm. ++ for you ;-)
Re: How to get the logged in user id
by rob_au (Abbot) on May 30, 2002 at 12:05 UTC
    Not surprisingly merlyn has already written a snippet of code which performs this task - It can be found here on this site.