使用 PHP 执行 bash 脚本,并输入命令

Executing bash script with PHP, and input commands

我正在尝试使用 PHP 执行 bash 脚本,但问题是脚本需要在执行过程中输入一些命令和信息。

这就是我正在使用的

$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh');
chdir($old_path);

脚本执行正常,但我无法在脚本上输入任何选项。

shell_exec() 和 exec() 无法 运行 交互脚本。为此,您需要一个真正的 shell。这是一个项目,给你一个真正的 Bash Shell: https://github.com/merlinthemagic/MTS

//if the script requires root access, change the second argument to "true".
$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', false);

//What string do you expect to show in the terminal just before the first input? Lets say your script simply deletes a file (/tmp/aFile.txt) using "rm". In that case the example would look like this: 

//this command will trigger your script and return once the shell displays "rm: remove regular file"

$shell->exeCmd("/my/path/script.sh", "rm: remove regular file");

//to delete we have to press "y", because the delete command returns to the shell prompt after pressing "y", there is no need for a delimiter.  

$shell->exeCmd("y");

//done

我确信脚本的 return 要复杂得多,但上面的示例为您提供了一个如何与 shell 交互的模型。

我还要提一下,您可能会考虑不使用 bash 脚本来执行一系列事件,而是使用 exeCmd() 方法一个一个地发出命令。这样您就可以处理 return 并将所有错误逻辑保留在 PHP 中,而不是将其拆分在 PHP 和 BASH 之间。

阅读文档,它会对你有所帮助。

proc_open() 在没有任何外部库的情况下使这成为可能:

$process = proc_open(
    'bash foo.sh',
    array( STDIN, STDOUT, STDERR ),
    $pipes,
    '/absolute/path/to/script/folder/'
);

if ( is_resource( $process ) ) {
    fclose( $pipes[0] );
    fclose( $pipes[1] );
    fclose( $pipes[2] );
    proc_close( $process );
}