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

时间:2016-08-21 01:04:30

标签: php bash exec

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

这就是我正在使用的

$(window).on('resize', function() {
  changeSrcset();
});

function changeSrcset() {
  var windowWidth = $(window).width();

  if (windowWidth <= 544) {
    $('.hero-image').attr('srcset', '/static/images/house-544.jpg');
  } else if (windowWidth <= 768) {
    $('.hero-image').attr('srcset', '/static/images/house-768.jpg');
  } else if (windowWidth <= 992) {
    $('.hero-image').attr('srcset', '/static/images/house-992.jpg');
  } else if (windowWidth <= 1200) {
    $('.hero-image').attr('srcset', '/static/images/house-1200.jpg');
  } else {
    $('.hero-image').attr('srcset', '/static/images/house-1915.jpg');
  }

  $('.hero-image').css('width', windowWidth);
}

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

2 个答案:

答案 0 :(得分:0)

shell_exec()和exec()无法运行交互式脚本。为此,你需要一个真正的外壳。这是一个为您提供真正的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

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

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

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

答案 1 :(得分:0)

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 );
}