Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Linux su twice

by breezykatt (Acolyte)
on Aug 09, 2016 at 19:44 UTC ( [id://1169431]=perlquestion: print w/replies, xml ) Need Help??

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 (Canon) 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?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1169431]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-04-24 09:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found