Search code examples
phpshellsshscp

PHP shell_exec returning an empty string, while executing the same command manually does not


I am currently having some weird behavior from shell_exec that I cant quite figure out.

This is my code:

        $cmd = ('sshpass -p PASSWORD scp -o StrictHostKeyChecking=no ../../UpdateFiles/' . $FILENAME . ' root@' . $IP . '://media/sdcard');
        $output = shell_exec($cmd);
        if (empty($output)){
            $cmd = ('sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no root@' . $IP . ' /sbin/start_sw_upgrade_process sdcard /media/sdcard ' . $FILENAME);
            $output = shell_exec($cmd);
            if (empty($output)){ $output = "No return from update command"; }
        }
        printf("%s",$output);

So, the first command works as intended, returning nothing only when successful. This can be easily verified, by the file now being in the sd card.

Once the file has been transferred to the other device, the next command should execute. This command should start a tool that should start using the file. As I am just using a dummy file it should return and error.

When I execute this code however, an empty string is returned, as it just prints "No return from update command"

However, if i go and execute the command manually at the same directory as the php file (filling in the variables manually ofc), there is an error being returned.

Whether the command is being executed but just not returning anything, or if the command doesn't execute at all, I am not too sure.

But I also use similar commands elsewhere such as:

        $cmd = ('sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no root@' . $IP . ' df | grep sdcard');
        $output = shell_exec($cmd);

In which case it works as expected. So I dont quite understand why it doesn't in this case.

Is this some stupid obvious mistake?

I have recently changed it so instead of printing "no return from update command" it prints the command that was just executed. When i copy that command and execute it the exact same situation, I get an output. Why does it only work manually?


Solution

  • Ok, so it took a while but i figured out what was the actual issue.

    So shell_exec() and exec() only read from sdtout, they do not read from sdterr. While a normal shell console will convert the errors to standard output, the functions in php, will not.

    As such the output of the functions was in fact empty, as the only output was errors. to fix this I appended the argument "1>&2" at the end of the command. This redirects the error output to the standard output. And now when the function is called I get an output instead of an empty string.