views:

338

answers:

0

I am trying to connect to some of my servers using PHP ssh2_connect method. If a server is not online, my script would attempt again at a later point of time. The problem am facing is that when a server is not available, the ssh2_connect method does not return a 'false' as mentioned in the php manuals, instead it waits until the script times out. Is there any way to force ssh2_connect function to return if it cannot connect immediately? Am using the following code..

<?php /* Notify the user if the server terminates the connection */

  function my_ssh_disconnect($reason, $message, $language) {
    printf("Server disconnected with reason code [%d] and message: %s\n",
            $reason, $message);
  }

  $methods = array(
             'kex' => 'diffie-hellman-group1-sha1',
             'client_to_server' => array(
                                   'crypt' => '3des-cbc',
                                   'comp' => 'none'),
             'server_to_client' => array(
                                  'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
                                  'comp' => 'none'));

  $callbacks = array('disconnect' => 'my_ssh_disconnect');

  // shell.example.com is replaced by my server addresses
  $connection = ssh2_connect('shell.example.com', 22, $methods, $callbacks);

  if (!$connection){
      die('Connection failed');
  }else{
     // authenticate and execute commands
  }

  ?>

The code works perfectly when the server is online. It would be great if someone can suggest a solution or workaround if server is offline. Servers run OpenSSH in case its related.