0

I am having trouble when try to set timeout for my ssh2_exec connection in PHP, so that when there is something wrong when running the command, it will release the executing thread and will not jam the whole web site. I have tried stream_set_timeout($stream,$seconds) but it seems not to work as expected.

Is there any ideas on this?

//run specified command (ssh)
    function runCMD($cmd){
        if (!($stream = ssh2_exec($this->conn, $cmd )))
        {
            echo "fail: unable to execute command\n";
            fclose($stream);
            return ERROR_SSH_EXEC_COMM;
        }

        sleep(1);
        stream_set_timeout($stream,5);//>>not work
        stream_set_blocking($stream, true);
        $res = stream_get_contents($stream);

        return $res;
    }
user2499325
  • 419
  • 1
  • 5
  • 15

3 Answers3

2

For anyone wondering how to set the timeout, there's a default_socket_timeout variable in php.ini that can be used to set the timeout for any socket-based connections in your current session.

You can check it by simply running

$timeStart = time();
ini_set("default_socket_timeout", 5);
$ssh = ssh2_connect('123.123.123.123');
echo (time() - $timeStart), PHP_EOL;
Slayer Birden
  • 3,664
  • 2
  • 22
  • 29
0

Here's how you could do that with phpseclib, a pure PHP SSH2 implementation:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

$ssh->setTimeout(5);
echo $ssh->exec('whatever');
?>

If you want to execute subsequent commands after that one you'll need to do $ssh->reset().

neubert
  • 15,947
  • 24
  • 120
  • 212
0

AFAIK, There are no true 'timeout' implementations in the php ssh2 specs.

The only solution that I have found for this problem can be found in this post here: PHP ssh2_connect() Implement A Timeout

Community
  • 1
  • 1
NodeNodeNode
  • 744
  • 5
  • 23