Php – How to use exec() in php in combination with ssh ‘hostname’ command

linuxPHPshellssh-tunnel

I have a simple script I'm trying to run:

<?php
print exec('whoami');
$output2 = exec('ssh someotherhost ls -l /path/to/dir',$output);
print_r($output);
print_r($output2);
print $output2;
?>

The goal of this script is to run a command on another networked server. If I run the above ssh command (replacing the dummy data with real data) from the command line:
ssh someotherhost ls -l /path/to/dir

It outputs the proper ls lines. However, when I run the above script from the same dir with the same command, it does not output in any of the three bottom print lines. However, the exec() with whoami at the top does print out as expected. So my question is, why does the first command work and not the second?

Note that the two networked servers are on an internal network and are setup with ssh network key pairings. The command works, just not from within php.

Thanks for your help.

Best Answer

PHP may be running the ssh command with a different user than you're doing it from the CLI. Maybe the user PHP is running it as doesn't have the servers key in its key file or something.

Personally, I would just use phpseclib, a pure PHP SSH implementation.