Answer the question
In order to leave comments, you need to log in
How to set timeout for ssh2_exec?
The application works with a remote server via SSH.
Sometimes it happens that the response from the server is very long (more than a minute), and, accordingly, the application hangs until it receives a response.
I need to somehow organize the response timeout so that if there is no response for more than 5 seconds, return, say, an empty response.
Tried using
set_time_limit(5);
ini_set("default_socket_timeout", 5);
stream_set_timeout($ssh, 5);
Does not help...
function sshExec($command)
{
$ssh = ssh2_connect('host', 22);
ssh2_auth_password($ssh, 'user', 'password');
$rStream = ssh2_exec($ssh, $command);
$rErrorStream = ssh2_fetch_stream($rStream, SSH2_STREAM_STDERR);
stream_set_blocking($rErrorStream, true);
stream_set_blocking($rStream, true);
$response = stream_get_contents($rStream);
$error = stream_get_contents($rErrorStream);
fclose($rErrorStream);
fclose($rStream);
return [
'response' => $response,
'error' => $error
];
}
Answer the question
In order to leave comments, you need to log in
First, you need to understand at what stage you need a timeout.
ssh2_connect does not support setting a timeout and nothing can be done about it. The way out is to use something else, like phpseclib .
For ssh2_exec you can monitor the timeout yourself. More or less like this:
$timeout = 30;
$timeStart = time();
while(!feof($rStream)) {
echo fread($rStream, 1024); //stdout
echo fread($rErrorStream, 1024); //stderr
if((time() - $timeStart) > $timeout) {
//timeout
break;
}
usleep(100); //prevent cpu overload
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question