首页 > 解决方案 > 当我尝试关闭 ssh2 连接时,没有回复

问题描述

我编写了一个 php 脚本,在 php7.3 的 apache 服务器上本地执行,执行以下操作:

  1. 通过 ssh2 访问服务器
  2. 检查文件是否存在
  3. 紧密连接
  4. 打印 json 数据对象作为响应。

除了关闭连接之外,脚本可以正常工作。如果我添加 ssh2_disconnect 函数,则不会返回任何响应。我错过了什么?这是我的代码:

<?php

error_reporting(1);
ini_set('display_errors', '1');

    $config = ["server"=>"10.1.201.1","port"=>"22","user"=>"root","password"=>"root","folder"=>"/"];
    $files = ["file1.pdf","file2.pdf"];
    $result = [];
    $ftpConnect = ssh2_connect($config['server'],$config['port']);
        ssh2_auth_password($ftpConnect,$config['user'],$config['password']);
    $sftp = ssh2_sftp($ftpConnect);

foreach ($files as $file){
    $fileExists = file_exists("ssh2.sftp://". intval($sftp) . $config['folder'] . $file);
        if($fileExists){
            $result[$file]= ["status"=>"Found"];
        }else $result[$file]= ["status"=>"Not found"];
}
//ssh2_disconnect($ftpConnect); only if uncommented, script wouldn't work
header('content-type:text/json; charset=UTF-8');
echo json_encode($result);
?>

标签: phpssh2-sftpssh2

解决方案


它似乎取决于版本。ssh2_disconnect是您使用的唯一功能,PECL ssh2 >= 1.0所有其他ssh2功能都可用于PECL ssh2 >= 0.9.0. 以下评论让我们认为 php >= 7 也是需要的。

http://php.net/manual/function.ssh2-disconnect.php#123413

以下是他建议在没有可用的情况下关闭连接的ssh2_disconnect方法:

$session = null; unset($session); // close connection

推荐阅读