To give background on my environment:
I have 3 machines A, B & C
A = Webserver, running a php website which basically acts as an interface for B & C
I recommend SSH2 to execute commands on remote machine. You can use pecl
to install it easily. After that, you may use ssh2_exec()
function to execute your commands and ssh2_fetch_stream()
function to get stderr. Example codes are listed below:
// start connection
$connection = ssh2_connect("your remote ip address", your port);
ssh2_auth_password($connection,"your user name","your passwd");
// connection established, start to execute codes
$stream = ssh2_exec($connection, "your command");
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
// block 2 streams simutaneously
stream_set_blocking($errorStream, true);
stream_set_blocking($stream,true);
// write stdout and stderr to log file
file_put_contents("your log file-path", date('Y-m-d H:i:s')."\nError: ".stream_get_contents($errorStream)."\nOutput: ".stream_get_contents($stream), FILE_APPEND)
// close 2 streams
fclose($errorStream);
fclose($stream);
// close remote connection
ssh2_exec($connection, 'exit');
Cheers.