I am using the PHP ssh2
library, and simply doing:
$ssh = ssh2_connect($hostname, $port);
The problem is I want to set a timeout, i.e. after 5 seconds stop trying to connect. As far as I can tell the ssh2 library does not support a timeout on connect natively. How can I implement a timeout wrapper?
I know this is an old thread, but the problem is still there. So, here is the solution for it.
ssh2_connect()
uses socket_connect()
. socket_connect
relies on the php ini configuration parameter default_socket_timeout
which is set by default to 60 seconds (http://php.net/manual/en/filesystem.configuration.php#ini.default-socket-timeout)
So, the easiest way to solve our problem is to change the ini setting at runtime to a value we want, and than back to the value set in the ini file so we avoid effecting other parts of our software. In the example below, the new values is set to 2 seconds.
$originalConnectionTimeout = ini_get('default_socket_timeout');
ini_set('default_socket_timeout', 2);
$connection = ssh2_connect('1.1.1.1');
ini_set('default_socket_timeout', $originalConnectionTimeout);
You can find further details about how ssh2 for php works by reading the source code of libssh2 (https://github.com/libssh2/libssh2).
I've been struggling with the same problem for a while. The fact is that trying to connect to a "dead" or unresponsive server with ssh2 will stall your application for as long as the target server's max connection time limit.
The easy way to detect beforehand if your instance is going to cause you trouble when shh-ing into it is to ping it (see if it's responsive).
function getPing($addr)
{
//First try a direct ping
$exec = exec("ping -c 3 -s 64 -t 64 ".$addr);
$array = explode("/", end(explode("=", $exec )) );
if(isset($pingVal[1]))
{
//There was a succesful ping response.
$pingVal = ceil($array[1]);
}
else
{
//A ping could not be sent, maybe the server is blocking them, we'll try a generic request.
$pingVal = callTarget($addr);
}
echo intval($pingVal)."ms";
if($pingVal > ["threshold"])
{
return false;
}
return true;
}
function callTarget($target)
{
$before = microtime();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target);
curl_setopt($ch, CURLOPT_NOBODY, true);
if (curl_exec($ch))
{
curl_close($ch);
return (microtime()-$before)*1000;
}
else
{
curl_close($ch);
return 9999;
}
}
This method allows you to get a faster response on the state of your server, so you know if you are about to waste your time ssh-ing into it.
the libssh2 library doesn't do the connect() by itself so it doesn't have to provide a timeout for that. libssh2 does however offer timeouts for the functions it does provide...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With