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

Hello, is there a function in Perl that allows me to switch user like the command 'su' in Unix ? Thanks very much...

Replies are listed 'Best First'.
Re: how to switch user
by gellyfish (Monsignor) on Jun 23, 2003 at 15:21 UTC

    You can either change the $< and $> builtin variables (real user id and effective user id respectively) to the appropriate numberic user ID (bearing in mind you have to have superuser privileges to do so) or use POSIX::setuid to change both at once (again you have to have the appropriate privileges to do so). Bear in mind that this is likely to be a one way operation - once you have become a less privileged user you will not be able to be switch back to the more privileged one. If you do need to switch back it might be appropriate to fork and change the user id in the child process.

    /J\
    
Re: how to switch user
by hardburn (Abbot) on Jun 23, 2003 at 15:27 UTC

    If you want to go from root to a normal user, that's easy. Just drop $EUID/$EGID to your real $UID/$GID (respecitivily):

    use English; # For saner var names # Do some stuff as root $EUID = $UID; $EGID = $GID; # Now we're running as a normal user

    Going up in privileges is harder. Probably the only realistic option is to execute the actual su (or maybe sudo) command and feed it the data to execute. (On GNU/Linux, you can pass in the data via the '-c' option to su, but this isn't portable).

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

      I'm not sure I understand your solution. If your script is running as root, chances are good that $UID and $EUID are already zero so your assignment won't do anything. Did you want to say something like this instead?
      unless ($UID) { $EUID = $unpriviledged_uid; $EGID = $unpriviledged_gid; } ...

      Note that setting $EUID lets you act like the user, but on AIX at least it doesn't prevent you (or a child process you spawn) from resetting this back to zero and becomming root again, which can have security implications if you really want to run a child process unpriviledged. You can try setting $UID directly, but that isn't supported on some systems (e.g. AIX again).

      bluto