Dukeatcoding
Dukeatcoding

Reputation: 1393

PHP SSH Connection via exec works when called from commandline but not via apache

My case is similar to PHP shell_exec running a shellscript with ssh but not the same.

Situation: I exchanged ssh-keys between the 2 servers, switched to the www-data user and connecting to the 2nd server via SSH works without password.

Test 1: ssh [email protected] Documents/run.sh list works fine when executed in shell

Test 2: Putting a simple PHP Exec in a PHP file works fine. It returns an Array and the Retval is 0

Test 3: Putting the exec into a "big" PHP script and calling it will result in Retval 255 (Fatal Error ?!?!?)

So at the moment I don't really understand why it isn't working. I tried to figure out more details about the retval 255 but didn't get far.

The difference must be somewhere in PHP5 vs PHP5 cli. But before I had to use OpenVPN it worked fine also via normal Apache call.

Upvotes: 1

Views: 5676

Answers (1)

LSerni
LSerni

Reputation: 57388

Generic

The first level of diagnosis for shell_exec problems is trying to get a more informative error by spawning the same command adding 2>&1, e.g. in your case

$retval = shell_exec("/path/to/ssh ... 2>&1");

and inspecting $retval.

Update

'Host key verification failed' means that the ~/.ssh/known_hosts for the user running Apache contains a different key. Check in the file both hostname and IP keys; in a pinch, delete both, log in as user www-data and reinstate the keys by connecting manually.

It is also possible, if connecting with a hostname, that the IPs have changed due to DHCP or different VPN tunnels being up, and that is not the host you're looking for.

In the case of SSH, it is possible to execute it with -vvv very violently verbose option, and then parse through the kilobytes of output searching for the source of the known_hosts file. It can also be useful to shell_exec diagnostic commands such as

$ret = shell_exec('set');

to see the value of HOME variable.

Upvotes: 5

Related Questions