PHP SSH exec() 失败:显然取决于导出的变量大小

PHP SSH exec() failure: evidently dependent on exported variable size

我正在使用如下格式的 SSH 命令向远程服务器发送一个相当大的字符串(存储在变量“$data”中):

$command= "ssh -l user subdomain.domain.com bin/prog <<<'$data'";
exec($command, $response, $status);

如果数据小于 130KB,执行行为正常,并且我从我的服务器得到了预期的响应。但是,如果 $data 大于大约 130KB,则执行命令立即 returns 一个 NULL 数组作为响应。

我不太确定这里发生了什么。起初我怀疑这是一个超时问题,但如果 $data 超过一定大小,命令 立即 失败。显然这里唯一的决定因素似乎是 $data 的大小。当数据小于130KB时,执行命令大约需要30-35秒。

欢迎任何意见。如果需要更多信息,请告诉我。

这里的核心问题与exec()函数缓冲区有关。

我们执行的通过 exec() 通过 SSH 发送数据的命令本质上是一个非常长的字符串。 PHP 的字符串大小限制约为 2GB。虽然 SSH 本身似乎能够传输任意数量的数据,但我们的 exec()'s 缓冲区似乎在 130KB 左右失败。在这些假设下,我们使用了一个名为 proc_open():

的 PHP 函数
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$cwd = '/tmp';
// $env = array('some_option' => 'aeiou');      // Our environment variables are loaded in the shell on login.
$env = NULL; 
$process = proc_open('ssh -l user subdomain.domain.com bin/prog', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    foreach($dataset as $dataline){
        fwrite($pipes[0], $dataline . "\n"); // Feed data down the pipe
    }

    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]); // echo out the reply from the bin/prog
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}

此过程直接来自手册。