run command line program and enter password from php

409 views Asked by At

I have a command line program which requires for the user to type a password in order to run. I want to run it and enter the password through a php script.

I have tried using proc_open, using the following code, but it does not work. It reads the input, but fwrite does not seem to do anything.

$cmd = "cmd /c command_line_program";

$descriptorspec = array(
    0 => array('pipe', 'r'),  //STDIN
    1 => array('pipe', 'w'),  //STDOUT
    2 => array('pipe', 'r'),  //STDERR
);
$process = proc_open(
    $cmd,
    $descriptorspec, $pipes, null, null);
if (is_resource($process)) {
    $buffer = "";
    // Read from the command's STDOUT until it's closed.
    while (!feof($pipes[1])) {
        $input = fread($pipes[1], 8192);
        $buffer .= $input;

        if (strpos($buffer, 'Password:') !== false){
            fwrite($pipes[0], "userpass\n");
        }
    }
    proc_close($process);
} else {
    echo 'Not a resource';
}

What am I doing wrong? Is there some other solution except proc_open? I am using windows and php 7.2.

1

There are 1 answers

0
ino On

According to PHP proc-open.php documentation and the comments bellow are recommendation to:

  1. close all three streams (store the return value issue):
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
  1. Assign the return value to a variable ( passing passwords to the process)
$exit_status = proc_close($process);

Both are missing in your code.