(PHP) 实时输出 proc_open

问题描述 投票:0回答:2

我已经尝试了很多次使用

flush()
使脚本同步工作,脚本仅打印第一个命令“gcloudcomputesshyellow”和“ls-la”的数据,我希望使脚本打印输出每执行一次
fputs()
.

<?php

$descr = array( 0 => array('pipe','r',),1 => array('pipe','w',),2 => array('pipe','w',),);
$pipes = array();
$process = proc_open("gcloud compute ssh yellow", $descr, $pipes);

if (is_resource($process)) {
    sleep(2);
    $commands = ["ls -la", "cd /home", "ls", "sudo ifconfig", "ls -l"];     
    foreach ($commands as $command) {    
        fputs($pipes[0], $command . " \n");
        while ($f = fgets($pipes[1])) {
            echo $f;
        }
    }
    fclose($pipes[0]);  
    fclose($pipes[1]);
    while ($f = fgets($pipes[2])) {
        echo "\n\n## ==>> ";
        echo $f;
    }
    fclose($pipes[2]);
    proc_close($process);

}

提前致谢

php exec proc-open passthru
2个回答
0
投票

我相信问题是你等待输入的循环。

fgets
只有遇到EOF才会返回false。否则它返回它读取的行;因为包含换行符,所以它不会返回任何可以类型转换为 false 的内容。您可以使用
stream_get_line()
代替,它不会返回 EOL 字符。请注意,这仍然需要您的命令在输出后返回一个空行,以便它可以计算为 false 并中断 while 循环。

<?php
$prog     = "gcloud compute ssh yellow";
$commands = ["ls -la", "cd /home", "ls", "sudo ifconfig", "ls -l"];
$descr    = [0 => ['pipe','r'], 1 => ['pipe','w'], 2 =>['pipe','w']];
$pipes    = [];
$process  = proc_open($prog, $descr, $pipes);

if (is_resource($process)) {
    sleep(2);
    foreach ($commands as $command) {
        fputs($pipes[0], $command . PHP_EOL);
        while ($f = stream_get_line($pipes[1], 256)) {
            echo $f . PHP_EOL;
        }
    }
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);
}

另一种选择是在循环外收集输出,尽管如果您需要知道什么输出来自哪个命令,这将需要您解析输出。

<?php
$prog     = "gcloud compute ssh yellow";
$commands = ["ls -la", "cd /home", "ls", "sudo ifconfig", "ls -l"];
$descr    = [0 => ['pipe','r'], 1 => ['pipe','w'], 2 =>['pipe','w']];
$pipes    = [];
$process  = proc_open($prog, $descr, $pipes);

if (is_resource($process)) {
    sleep(2);
    foreach ($commands as $command) {
        fputs($pipes[0], $command . PHP_EOL);
    }
    fclose($pipes[0]);
    $return = stream_get_contents($pipes[1]);
    $errors = stream_get_contents($pipes[2]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);
}

0
投票

我能够在管理中使用我的 Wordpress 插件使用 out.log 执行 shell_exec 并显示其他 AJAX 函数的最后一行。

你可以去我的 Github 仓库看看它是什么样的,在这个文件的函数 my_url() 的第 516 行,my_dl() 将更新结果 DIV。

https://github.com/Jerl92/McPlayer/blob/master/admin/partials/McPlayer-admin-bulk-add-album.php

这是执行长 shell_exec 命令的一种方法,这将更新输出区域。

谢谢,

© www.soinside.com 2019 - 2024. All rights reserved.