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

I need $output in the code below to be the output from the passwd command ($passwd_cmd). Currently it appears to be the output from the su command ($su_cmd). How can I go about capturing this?
#!/usr/bin/perl my $verbose=1; my $user=@ARGV[0]; my $passwd_cmd="/usr/bin/passwd"; my $su_cmd="/bin/su $user -c"; ####################################################### ####################################################### my $cmd=$su_cmd . $passwd_cmd . " $user"; print "command=$cmd\n" if $verbose; my $output=system($cmd); print "output=$output\n" if $verbose; exit $output;
By the way, some may ask why I need to do this. The code above is ran as root, but due to the complexities of the calling application which I have no control over, the passwd command must be ran as the user actually changing his password. The code above is part of a larger program.

How can I capture the output of the passwd command and not the su command as I appear to be doing now? Thanks for your help in advance.

Replies are listed 'Best First'.
Re: Capture output from command under su
by shmem (Chancellor) on May 05, 2007 at 19:38 UTC
    if you are interested in the exit status (not the output, as grep pointed out) of /usr/bin/passwd, you could use
    $cmd = "/bin/su $user -c '/usr/bin/passwd $user; exit \$?'";

    as your constructed $cmd, although I'm pretty sure that su sets its own exit status to that of the invoked program.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Capture output from command under su
by grep (Monsignor) on May 05, 2007 at 18:23 UTC
    Straight out of system doc (my own emphasis added):

    The return value is the exit status of the program as returned by the wait call. To get the actual exit value, shift right by eight (see below). See also exec. This is not what you want to use to capture the output from a command, for that you should use merely backticks or qx//, as described in "`STRING`" in perlop. Return value of -1 indicates a failure to start the program or an error of the wait(2) system call (inspect $! for the reason).

    grep
    1)Gain XP 2)??? 3)Profit