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

Currently I have a line in my perl code that does this:

use IPC::Run qw(run); my ($stdout, $stderr); run [ qw/perl -e/, $code ], '<', \$arg, '>>', \$stdout, '2>>', \$stder +r;

I use IPC::Run::run to run some perl code.

I want to run it under a separate user : limiteduser, I'm probably not thinking in *nix terms so I'm just not sure about how to do this? Should I do:

run [ qw/sudo -u limiteduser perl -e/, $code ], '<', \$arg, '>>', \$stdout, '2>>', \$stderr;

OR should I use Sudo to do this?

My Goal is that if there is a system call inside $code then it should fail, as limiteduser doesn't have such privileges

Replies are listed 'Best First'.
Re: run perl -e programmatically as another user
by tobyink (Canon) on Mar 05, 2013 at 14:30 UTC

    If the main script is being run as root, you can easily switch user by assigning to $< and $>

    use strict; use warnings; use IPC::Run 'run'; my $code = q{ print "Real user id: $<\n"; warn "Effective user id: $>\n"; }; my ($stdout, $stderr); { local $< = local $> = 500; run [ qw/perl -e/, $code ], '>>', \$stdout, '2>>', \$stderr; } print "STDOUT was: $stdout"; print "STDERR was: $stderr";
    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
Re: run perl -e programmatically as another user
by blue_cowdawg (Monsignor) on Mar 05, 2013 at 14:35 UTC
        OR should I use Sudo to do this?

    That would be my strategy as long as you remember a few caveats:

    1. The first and most obvious is that the sudoers file is properly configured to accomodate what you are trying to do.
    2. Pay close attention to the details of file/directory permissions and ensure that whereever you are opening files you have proper permissions as the user the command is running as.
    3. Answer yourself: do you really need a script to execute a script?
    That last point I bring up as a artifact of my not understanding from the small context you've given why you feel the need to do this. Would cron do the same thing for you (a crontab in the non-priveleged user's account)?


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg