PHP Exec command - How to pass input to a series of questions

前端 未结 3 1558
误落风尘
误落风尘 2021-01-12 11:47

I have a program on my linux server that asks the same series of questions each time it executes and then provides several lines of output. My goal is to automate the input

相关标签:
3条回答
  • 2021-01-12 12:25
    $out = array();
    //add elements/parameters/input to array
    string $execpath = "my/path/program ";
    foreach($out as $parameter) {
      $execpath += $parameter;
      //$execpath += "-"+$execpath; use this if you need to add a '-' in front of your parameters.
    }
    exec($execpath);
    
    0 讨论(0)
  • 2021-01-12 12:29

    First up, just to let you know that you're trying to reinvent the wheel. What you're really looking for is expect(1), which is a command-line utility intended to do exactly what you want without involving PHP.

    However, if you really want to write your own PHP code you need to use proc_open. Here are some good code examples on reading from STDOUT and writing to STDIN of the child process using proc_open:

    • http://www.php.net/manual/en/function.proc-open.php#79665
    • How to pass variables as stdin into command line from PHP
    • http://camposer-techie.blogspot.com/2010/08/ejecutando-comandos-sobre-un-programa.html (this one is in Spanish, sorry, but the code is good)

    Finally, there is also an Expect PECL module for PHP.

    Hope this helps.

    0 讨论(0)
  • 2021-01-12 12:31

    Just add the arguments to the exec line.

    exec("/path/to/programname $arg1 $arg2 $arg3");
    

    ... but don't forget to apply escapeshellarg() on every argument! Otherwise, you're vulnerable to injected malicious code.

    0 讨论(0)
提交回复
热议问题