【问题标题】:ssh2_exec: wait end of a process to run nextssh2_exec:等待下一个进程结束运行
【发布时间】:2018-02-06 19:02:51
【问题描述】:

我正在使用 ssh2_exec 运行命令,但看起来它在 $stream1 进程结束之前运行 $stream2。如何仅在 $stream1 结束后运行 $stream2?

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream1= ssh2_exec($connection, 'command to run');

$stream2 = ssh2_exec($connection, 'command to run 2');

?>

【问题讨论】:

    标签: php ssh


    【解决方案1】:

    问题已解决:

    @Barmar 建议我看看 php.net/manual/en/function.ssh2-exec.php#59324

    我通过以下方式解决了问题:

    <?php
    $connection = ssh2_connect('shell.example.com', 22);
    ssh2_auth_password($connection, 'username', 'password');
    
    $stream1= ssh2_exec($connection, 'command to run');
    
    stream_set_blocking($stream1, true);
    
    // The command may not finish properly if the stream is not read to end
    $output = stream_get_contents($stream1);
    
    $stream2 = ssh2_exec($connection, 'command to run 2');
    
    ?>
    

    【讨论】:

      【解决方案2】:

      默认情况下不启用阻止的事实是愚蠢的。这就是为什么我更喜欢SSH by phpseclib 的原因。 phpseclib 的东西就像预期的那样工作。例如。

      <?php
      include('Net/SSH2.php');
      
      $ssh = new Net_SSH2('shell.example.com', 22);
      $ssh->login('username', 'password');
      
      $output = $ssh->exec('command to run');
      $ssh->exec('command to run 2');
      ?>
      

      【讨论】:

        【解决方案3】:

        从第一个流中读取所有内容。完成后,您就知道命令已完成。

        $stream1= ssh2_exec($connection, 'command to run');
        stream_get_contents($stream1); // Wait for command to finish
        fclose($stream1);
        
        $stream2 = ssh2_exec($connection, 'command to run 2');
        

        【讨论】:

        • 现在它在 $stream2 行上给我一个错误。 PHP 警告:ssh2_exec(): Unable to request an channel from remote host in XXX.php on line 28
        • 当我删除带有 stream_get_contents 的行时,我没有收到任何错误。
        • 抱歉,我对 ssh2 扩展不够熟悉,不知道为什么会发生这种情况或如何解决它。
        • 试试我刚刚添加的fclose。我从这里得到了这个想法:php.net/manual/en/function.ssh2-exec.php#53691
        • 如果这不起作用,您可能不得不在这里求助于更复杂的解决方案:php.net/manual/en/function.ssh2-exec.php#59324
        猜你喜欢
        • 1970-01-01
        • 2013-12-03
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-10
        相关资源
        最近更新 更多