So, I do one simple thing, firstly, I execute the command through ssh2_exec (after successful authentication), and then I read the response in a variable. My code is below (no authentication)
try {
$stdout_stream = ssh2_exec($this->connection, $_cmd);
$stderr_stream = ssh2_fetch_stream($stdout_stream, \SSH2_STREAM_STDERR);
} catch (Exception $e) {
$std_output = $e->getMessage();
return false;
}
$output = "";
while (!feof($stdout_stream)) {
$output .= fgets($stdout_stream, 4096);
}
while (!feof($stderr_stream)) {
$output .= fgets($stderr_stream, 4096);
}
fclose($stdout_stream);
fclose($stderr_stream);
return $output;
For example, I try to execute such cmd:
sudo service httpd stop && sudo service httpd start
So, when the command is executed well, everything is fine, the answer
Shutdown httpd: [OK] Start httpd: [OK]
But when I try, for example, to execute such a command without sudo
service httpd stop && service httpd start
I know that the server says something like โcommand not foundโ or something like this, but I cannot get this error, this script runs endlessly.
I tried to rewrite my code this way (or with others similar to this)
$dataString = fgets($stdout_stream);
if($dataString == "\n" || $dataString == "\r\n" || $dataString == "") {
//var_dump("Empty line found.");
}
if($dataString === false && !feof($stdout_stream)) {
//var_dump("not string");
} elseif($dataString === false && feof($stdout_stream)) {
//var_dump("We are at the end of the file.\n");
break;
} else {
//else all is good, process line read in
$output .= $dataString;
}
}
but the result is the same.
So, the problem is that we cannot say in advance what an infinite loop $stdout_streamor follows $stderr_stream.
PHP 5.3.