Search code examples
phpwindowssymfonysshsymfony-process

Feed key passphrase to external SSH command on Windows


I'm using Symfony Process to run the SSH client bundled with Windows in a command-line PHP script. Remote server settings are stored in C:\Users\MYUSERNAMEHERE\.ssh\config file, connection is established with a private key and I run the command manually with my personal user.

The prompt for private key password is handled nicely if I don't make any special arrangement: I type it when prompted and all's good. However, that imposes a few restrictions:

  • I can't type the password until prior steps of the script complete.
  • I need to type it every time I run SSH in my script.

I'd rather ask for password myself and then feed SSH with it as many times as needed. I've been trying to use process input for this, but nothing I've attempted works. Depending on what I do I get two outcomes:

  • Script still halts with "Enter passphrase for key" prompt.
  • Process runs and fails, exit code is null, process stdout and stderr are blank and terminal shows "Enter passphrase for key".

This is one of the iterations:

$input = new InputStream();
$process = new Process('ssh connectionnamehere ls -Al');
$process->setInput($input);
$process->start();
//$process->wait();
$input->write('MYSSHPASSWORDHERE'. "\r\n"); // Temporarily hard-coded until I figure this out
$input->close();
var_dump(
    $process->isSuccessful(),
    $process->getExitCode(),
    $process->getExitCodeText(),
    $process->getOutput(),
    $process->getIncrementalOutput(),
    $process->getErrorOutput(),
    $process->getIncrementalErrorOutput()
);
bool(false)
NULL
NULL
string(0) ""
string(0) ""
string(0) ""
string(0) ""
Enter passphrase for key 'C:\Users\MYUSERNAMEHERE\.ssh\id_rsa-redacted': 

What am I missing?


Solution

  • The problem is that OpenSSH command-line tools do not read passkey from stdin, so it's just not possible to use Symfony Process, or any other PHP library, to provide it. It seems to be an intentional behaviour for security reasons.

    If you need to streamline process execution in such a way that user doesn't need to type password several times, you need to look somewhere else: