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.