SSH连接在重负载下失败

时间:2012-04-21 06:42:02

标签: php ssh

$con = ssh2_connect($host, 22);
ssh2_auth_password($con, $rem_acc, $pass);
ssh2_scp_send($con,$rand.".gz","./".$rand.".gz");
$stream = ssh2_exec($con, "./exeonserv.sh ".$rand);

只要我将负载保持在PHP脚本每秒2个以下的请求(脚本中有2个SSH连接,每秒4个连接),这样就可以了。

但是当它超过每秒2个请求时,连接开始失败,日志中出现此错误:

  

[Sat Apr 21 11:51:40 2012] [错误] [client 172.16.57.97] PHP警告:ssh2_connect():启动SSH连接时出错(-1):在/ var / www / fsproj中获取横幅失败第105行上的/result.php
  [Sat Apr 21 11:51:40 2012] [错误] [client 172.16.57.97] PHP警告:ssh2_connect():无法连接到第105行的/var/www/fsproj/result.php中的localhost

我使用以下代码尝试解决问题,但是如果持续负载大于2req / sec。它最终会增加响应时间

$con=false;    
while(!$con)
{
    $con = ssh2_connect($host, 22);
}

是否可以打开SSH连接的最大速率上限?如果是这样我可以在哪里更改该值? (或任何其他解决方案?)

我在Ubuntu上使用Apache

2 个答案:

答案 0 :(得分:2)

看一下man sshd_config,以下部分似乎控制了一次可以打开的最大SSH连接数以及最大并发连接尝试次数。您需要使用所需的设置修改/etc/ssh/sshd_config

     MaxSessions
             Specifies the maximum number of open sessions permitted per net-
             work connection.  The default is 10.

     MaxStartups
             Specifies the maximum number of concurrent unauthenticated con-
             nections to the SSH daemon.  Additional connections will be
             dropped until authentication succeeds or the LoginGraceTime
             expires for a connection.  The default is 10.

             Alternatively, random early drop can be enabled by specifying the
             three colon separated values ``start:rate:full'' (e.g.
             "10:30:60").  sshd(8) will refuse connection attempts with a
             probability of ``rate/100'' (30%) if there are currently
             ``start'' (10) unauthenticated connections.  The probability
             increases linearly and all connection attempts are refused if the
             number of unauthenticated connections reaches ``full'' (60).

此外,对于您尝试连接到服务器的示例,您可能希望在尝试连接失败后添加sleep。如果没有这种退避并且服务器被淹没,您的脚本可能会通过尝试通过连接尝试更多地使服务器充满来使事情变得更糟。

答案 1 :(得分:1)

老实说,我会使用phpseclib, a pure PHP SSH implementation

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

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

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

phpseclib比libssh2更便携,您可以使用phpseclib获取日志,这可能有助于诊断您的问题。