PHP ssh2_connect()实现超时 [英] PHP ssh2_connect() Implement A Timeout

查看:73
本文介绍了PHP ssh2_connect()实现超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP ssh2库,并且只是在做:

I am using the PHP ssh2 library, and simply doing:

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

问题是我要设置超时,即5秒钟后停止尝试连接.据我所知ssh2库不支持本地连接超时.如何实现超时包装器?

The problem is 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 timeout on connect natively. How can I implement a timeout wrapper?

推荐答案

我知道这是一个旧线程,但是问题仍然存在.因此,这是解决方案.

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

ssh2_connect()使用socket_connect(). socket_connect依赖于php ini配置参数default_socket_timeout,该参数默认设置为60秒(

ssh2_connect() uses socket_connect(). socket_connect relies on the php ini configuration parameter default_socket_timeout which is set by default to 60 seconds (http://php.net/manual/en/filesystem.configuration.php#ini.default-socket-timeout)

因此,解决问题的最简单方法是在运行时将ini设置更改为所需的值,而不是将其更改为ini文件中设置的值,从而避免影响软件的其他部分.在下面的示例中,新值设置为2秒.

So, the easiest way to solve our problem is to change the ini setting at runtime to a value we want, and than back to the value set in the ini file so we avoid effecting other parts of our software. In the example below, the new values is 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);

通过阅读libssh2的源代码,您可以找到有关ssh2 for php的工作方式的更多详细信息( https://github .com/libssh2/libssh2 ).

You can find further details about how ssh2 for php works by reading the source code of libssh2 (https://github.com/libssh2/libssh2).

这篇关于PHP ssh2_connect()实现超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆