Controlling an interactive process with PHP using Symfony Process

倖福魔咒の 提交于 2019-12-04 05:35:35

Finally found a solution to this problem after reading the source for ssh-add and by reading this very old article from Wez Furlong where he talks about adding PTY support to PHP.

To quote the article:

What this does is similar to creating a pipe to the process, but instead creates master (for your script) and slave (for the process you're running) pty handles using the /dev/ptmx interface of your OS. This allows you to send to, and capture data from, applications that open /dev/tty explicitly--and this is generally done when interactively prompting for a password.

Turns out Symfony Process also supports PTY so the original code only needed a couple of changes. First I need to specify I want to use PTY instead of pipes by calling setPty(true). Then I need to simulate that the user has pressed ENTER after inputting the password simply by appending a line feed to the input.

The final code would look something like this (with comments on the changed lines)

use Symfony\Component\Process\Process;

$keyPath = '<path to key>';
$keyPassword = '<password for unlocking the key>';
$socketPath = '<path to ssh-agent socket>';

$sshAdd = new Process(
    "ssh-add {$keyPath}",
    null,
    [
        'SSH_AUTH_SOCK' => $socketPath
    ],
    $keyPassword . "\n"   // Append a line feed to simulate pressing ENTER
);
$sshAdd->setPty(true);   // Use PTY instead of the default pipes
$sshAdd->run();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!