stream_set_timeout not working for ssh2_exec in PHP

瘦欲@ 提交于 2020-01-06 08:14:24

问题


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;
    }

回答1:


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;



回答2:


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().




回答3:


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



来源:https://stackoverflow.com/questions/17468374/stream-set-timeout-not-working-for-ssh2-exec-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!