Mike Mike - 1 year ago 56
Bash Question

Use PHP to run a shell script

Now I know this question has been asked a few times, but I've followed everyone's suggestions and I'm still stumped.

I have a shell script (/var/www/scripts/test.sh):


echo "export start"
ssh -i $key $ssh_con "php /file/location/ service:batch:job export --env=prod"
echo "export complete"

the script has the following permissions:

-rwxrwxrwx 1 www-data www-data 1792 Jun 3 10:44 bash_script.sh*

the code im running in php is:

try {
$outbuf=shell_exec("sh /var/www/scripts/test.sh");
echo "<pre>".$outbuf."</pre>";

}catch (Exception $e) { //while an error has occured
echo "==> Error: ".$e->getMessage();

When I view this from a web browser I get:

export start
export complete

does not run.

I can confirm that php.ini allows

I feel like I'm missing something obvious.

Answer Source

Since your script is already executable, you should call it directly. Just put a shebang on top and you've removed one layer of complication.

Next, redirect standard error from ssh to standard output so that PHP can show you any error messages.

I'd be willing to bet that you'll find ssh is complaining about the key. You'll need to put that key file somewhere else. An SSH key in a user directory typically has 600 permissions.

Finally, shell_exec() won't throw anything you can catch. If you want to know if the process succeeded, you can use a different function. In that case it might be a good idea to pass on the exit status that matters.

So, to sum up:


echo "export start"
ssh -i "$key" "$ssh_con" "php /file/location/ service:batch:job export --env=prod" 2>&1
echo "export complete"
exit ssh_result

And then:

exec("/var/www/scripts/test.sh", $outbuf, $result);
$outbuf = htmlspecialchars(implode("\n", $outbuf));
echo "Exited with code $result.";
echo "<pre>$outbuf</pre>";