Mike Mike - 6 months ago 21
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):

ssh_con="ssh-user@x.x.x.x"
key="/home/user/.ssh/key"

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();
exit();
}


When I view this from a web browser I get:

export start
export complete


However,
ssh
does not run.

I can confirm that php.ini allows
exec
and
shell_exec
.

I feel like I'm missing something obvious.

Answer

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:

#!/bin/sh
ssh_con="ssh-user@x.x.x.x"
key="/home/user/.ssh/key"

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

And then:

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