in reply to run shell command as another user

G'day ox1d0,

Welcome to the monastery.

You need some basic debugging here.

If

system ("su -l - $user -c \'$action > DBlist.txt && cat DBlist.txt\'") +;

doesn't work, but

system ("su -l - MyRealuser -c \'$action > DBlist.txt && cat DBlist.tx +t\'");

does work, then the only difference between them is $user and MyRealuser.

Use a print statement like this:

print ">>>$user<<<\n";

Do you get:

>>>some_username<<<

or:

>>>some_username <<<

If the former, replace MyRealuser with some_username (in the system() command that worked), and see if it still works. If not, see system to learn about checking for errors. Maybe there's a problem with some_username's account or privileges.

If the latter, the newline after $user may be the culprit. You can fix that with:

chomp(my $user = $line);

I also note that you're using the same $line variable when reading from the EXEC and $cmd filehandles. Unless there's some specific reason for doing this, I'd use different variables, e.g.

while(my $exec_line = <EXEC>) { ... while (my $cmd_line = <$cmd>) { ... } }

Even if using the same variable isn't causing any problems now, it could well turn into a hard-to-track-down bug in the future following some (seemingly innocuous) modification.

-- Ken

Replies are listed 'Best First'.
Re^2: run shell command as another user
by ox1d0 (Acolyte) on Apr 19, 2014 at 03:19 UTC
    Hello Ken, seems that the problem is in fact with system() I've tried with
    #my @command = ("su - $user -c id") #################################### #system ("su - $user"); #this Works# #################################### #system ("@command") == 0 or die "system @command failed: $?"; #exec ('su - $user -c $action') or print STDERR "couldn't exec foo: +$!"; #exec("/bin/su","-",$user,$action); #system ("su", "-", $user, "-c", "/bin/bash -c $action"); #system ("su - $user -c /bin/bash -c $action"); #system "sudo","su","-" => $user, -c => $action;

    but each one fails!!

    also i tried these modules, same result ..

    use warnings; use diagnostics; use strict; use Shell::Source; use Shell; my $action="\'Anything\'"; my $user="RealUser"; my $sh = Shell->new; say "$user"; say "$action "; print $sh->sudo("su -l - $user --command $action");

    I start to thinking if my Gentoo has problems , I'll try in another system...

    btw I've checked for $user seems that is good, just before function.

    thanks..