首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PHP执行bash脚本,并输入命令

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

Stack Overflow用户
提问于 2016-08-21 01:04:29
回答 2查看 980关注 0票数 2

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

这就是我要用的

代码语言:javascript
复制
$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh');
chdir($old_path);

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-26 13:19:37

shell_exec()和exec()不能运行交互式脚本。为此你需要一个真正的外壳。下面是一个给您一个真正的Bash的项目:https://github.com/merlinthemagic/MTS

代码语言:javascript
复制
//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

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

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

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

票数 0
EN

Stack Overflow用户

发布于 2021-05-17 19:11:00

proc_open()使得在没有任何外部库的情况下这样做是可能的:

代码语言:javascript
复制
$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 );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39060011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档