[Israel.pm] How to use Unix "su" (=switch user) command

David Baird david.baird at cmcrossroads.com
Wed Sep 22 00:38:26 PDT 2004


> I need from a perl script to connect another user by "su" 
> command - switch user -
> and run another script in this user.
> How can I implement it?
> 
> Since I'm not in perl at perl.org.il group, I will be happy if 
> you send the answer
> to my private inbox: shulamito at amdocs.com

I have a perl script which does this with sudo and changing the uid in
the script. It has this header:

#!/bin/sh
sudo /usr/bin/perl -x $0
exit

#!perl
use English '-no-match-vars';

And in the script, it does the following:

# must run as effective root
( $EUID == 0 )   or die "$0: must run as root\n";
POSIX::setuid(0) or die "$0: cannot setuid to root: $!\n";

I can then become the user which started the command:

$UID  = $ENV{SUDO_UID};
$EGID = $ENV{SUDO_GID};

I can also do this temporarily for some commands:

{
    local $UID = $ENV{SUDO_UID};
    cp($s, $t, $flags);
}

Read more in "perldoc perlvar" for information on $UID, $GID, $EGID and
$EUID. Read more in "perldoc POSIX" about setuid().

Read "man sudo" and "man sudoers" on how to establish sudo permissions
to users.

-David




More information about the Perl mailing list