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

Hi, I am wondering if it is possible to switch users twice, run a command and then exit back to the logged in user? For example:

system("sudo su");
system("su - newuser");
system("/path/to/file");
system("exit");
system("exit");

or

system("sudo su; su - newuser; ./path/to/file; exit; exit;");

thanks

Replies are listed 'Best First'.
Re: Linux su twice (updated)
by haukex (Archbishop) on Aug 09, 2016 at 20:16 UTC

    Hi breezykatt,

    Why twice?

    Your first form won't work because each call to system spawns a new, independent shell.

    Whether or not it's the best architecture for one script to call another under a different user is something I can't tell without knowing more about the problem you're trying to solve. But assuming you know what you're doing and why, this should work:

    system("sudo -u newuser /path/to/file") == 0 or die "system failed, \$?=$?";

    Update: I believe the sudo equivalent of su - (aka su -l) is sudo -i, so if you need that, use sudo -iu newuser /path/to/file

    Hope this helps,
    -- Hauke D

      Thanks - just wanted to provide an update. I ended up using puppet since we had that in our lab and was able to use their method to run the necessary commands since they already had it set up to distribute the software across nodes.
Re: Linux su twice
by soonix (Chancellor) on Aug 09, 2016 at 22:02 UTC
    Seconding haukex. You see it as a sequence of commands, but in fact they are nested. You could try something like
    system('echo "echo /path/to/file | su - newuser" | sudo su');
Re: Linux su twice
by jesuashok (Curate) on Aug 10, 2016 at 03:46 UTC
    breezykatt - Kindly provide more context around what you are trying to achieve. Are you trying to execute sequence of commands as two different user from the same Perl script?