【问题标题】:PHP - How to keep a Command Shell open for executing multiple commands?PHP - 如何保持打开命令外壳以执行多个命令?
【发布时间】:2014-10-17 09:45:50
【问题描述】:

您好,我正在尝试在 Windows 机器上使用 PHP 执行多个命令。我试过这段代码:

<?php
$output= shell_exec("powershell.exe");
$output2= shell_exec("write-host gokul");
shell_exec("exit");
echo( '<pre>' );
echo( $output );
echo( $output2 );
echo( '</pre>' );
?>

PHP 使用新的 shell 执行每个命令,并在完成时关闭它!

我知道每个 'shell_exec' 都会创建一个新的 shell 并控制等待命令执行完成。如何创建一个在我关闭之前一直在后台打开的 shell

不确定 'proc_open' 或 'popen' 是否有帮助?

更新 当我尝试 PROC_OPEN()

$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", "error.txt", "a") // stderr is a file to write to
);    
$process = proc_open('cmd.exe', $descriptorspec, $pipes);

if (is_resource($process)) {
    fwrite($pipes[0], 'dir');
    fwrite($pipes[0], 'powershell.exe');
    fwrite($pipes[0], 'write-host gokul');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    proc_close($process);
}

它只打印提示。我真的可以使用 proc_open 来执行多个命令吗?如果有,怎么做?

Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\wamp\bin\apache\Apache2.2.17>More?

【问题讨论】:

  • 是的,您可以使用proc_open。查看它的手册页:php.net/manual/en/function.proc-open.php
  • @hek2mgl 嗨,我试过 proc_open。请查看问题编辑和帮助。
  • 您是否尝试过使用“&&”执行命令,请参阅:command1 && command2。我现在没有任何 Win 机器,但这通常适用于 *Nix 机器
  • @GPcyborg 您错过了在每个命令后添加新行
  • @hek2mgl 嘿,太棒了!它适用于“cmd”中的所有命令,但不能调用“powershell.exe”。我什至尝试将“powershell.exe”传递给 proc_open 而不是“cmd.exe”。不过,您的想法解决了基本问题。添加一个答案,我会将其标记为正确。

标签: php shell process


【解决方案1】:

使用proc_open 是正确的尝试,但您需要以换行符结束每个命令。就像您在 shell 会话中手动键入命令一样。

应该是这样的:

fwrite($pipes[0], 'dir' . PHP_EOL);
fwrite($pipes[0], 'powershell.exe' . PHP_EOL);
fwrite($pipes[0], 'write-host gokul' . PHP_EOL);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 2021-11-21
    • 1970-01-01
    • 2012-10-03
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多