PHP ssh2_connect () Deploy timeout

I am using the PHP ssh2 library and just doing:

 $ssh = ssh2_connect($hostname, $port); 

The problem is that 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 connection timeout. How can I implement a timeout shell?

+6
source share
3 answers

I have 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 stop your application until the maximum connection time for the target server is maximum.

An easy way to detect in advance if your instance will cause you problems when you log in to check it (see if it responds).

 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 quickly respond to the status of your server, so you know whether you are going to spend your time to save time.

+2
source

I know this is an old thread, but the problem still exists. So here is the solution for it.

ssh2_connect() uses socket_connect() . socket_connect depends on the php ini default_socket_timeout configuration parameter, which is set to 60 seconds by default ( 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 the value we need, and not return to the value set in the ini file so that we do not use other parts of our software. In the example below, the new values ​​are 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 more information on how ssh2 for php works by reading the libssh2 source code ( https://github.com/libssh2/libssh2 ).

+1
source

the libssh2 library itself does not execute connect (), so it does not need to provide a timeout for this. However, libssh2 offers timeouts for the functions it provides ...

0
source

Source: https://habr.com/ru/post/916517/


All Articles