Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js child_process exec, stdin not being passed through to ssh

I have the following Node.js code to ssh into a server and it works great forwarding stdout, but whenever I type anything it is not forwarding to the server. How do I forward my local stdin to the ssh connections stdin?

var command = 'ssh -tt -i ' + keyPath + ' -o StrictHostKeyChecking=no ubuntu@' + hostIp;

var ssh = child_proc.exec(command, {
    env: process.env
});

ssh.stdout.on('data', function (data) {
    console.log(data.toString());
});

ssh.stderr.on('data', function (data) {
    console.error(data.toString());
});

ssh.on('exit', function (code) {
    process.exit(code);
});
like image 479
Justin Avatar asked Jul 22 '26 06:07

Justin


1 Answers

There's two ways to go about this if you want to pipe the process.stdin to the child process:

  • Child processes have a stdin property that represents the stdin of the child process. So all you should need to do is add process.stdin.pipe(ssh.stdin)

  • You can specify a custom stdio when spawning the process to tell it what to use for the child process's stdin:

    child_proc.exec(command, { env: process.env, stdio: [process.stdin, 'pipe', 'pipe'] })
    

Also, on a semi-related note, if you want to avoid spawning child processes and have more programmatic control over and/or have more lightweight ssh/sftp connections, there is the ssh2 module.

like image 69
mscdex Avatar answered Jul 23 '26 20:07

mscdex