Node.js的child_process exec,stdin无法传递到ssh

3
我有以下的Node.js代码用于ssh登录到服务器并成功地转发stdout,但是当我输入任何内容时,它不会被转发到服务器。如何将本地的stdin转发到ssh连接的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);
});
1个回答

6

如果你想将process.stdin传输到子进程,有两种方法:

  • 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'] })
    

此外,如果您想避免产生子进程,并且希望对ssh / sftp连接具有更多的编程控制和/或更轻量级,请考虑使用ssh2模块。


使用process.stdin.pipe(ssh.stdin)似乎大部分情况下都能正常工作,但它会复制您输入的命令。例如:https://gist.github.com/nodesocket/cb7ffc11b764dc642325 - Justin
1
如果您不想显示本地输入,可以使用 process.stdin.setRawMode(true) 启用原始模式。 - mscdex
几乎一样,除了我输入的每个字符现在都在新行上。请参见:https://gist.github.com/nodesocket/cb7ffc11b764dc642325 - Justin
3
请将您的 ssh.stdoutssh.stderr 处理程序更改为相应的管道方式,即 ssh.stdout.pipe(process.stdout)ssh.stderr.pipe(process.stderr)。原因是 console.* 方法会在输出末尾添加一个换行符。 - mscdex
答案应更新以包括上面评论中的信息。 - Daniel Kobe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接