So I do one simple thing, firstly I exec command via ssh2_exec (after success authenticate) and then read answer in variable. My code below (without authenticate)
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 command executes well everything is good, response is
Shutting down httpd: [ OK ]Starting httpd: [ OK ]
But when I try for instance to execute such command without sudo
service httpd stop && service httpd start
I know server says something like "command not found" or like this, but I can't get this error, this script executes infinitely.
I tried to rewrite my code in this manner (or another similiar 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 result is the same.
So the problem is we cannot say in advance what cause infinite loop $stdout_stream
or $stderr_stream
.
I am using PHP 5.3.