child_process.spawn 无法交互式执行命令ssh-keygen、ssh-copy-id
发布于 6 年前 作者 lyt308012546 6204 次浏览 来自 问答

期望

通过node执行ssh-keygen无需交互式输入密钥,因为要做自动化,密码是事先知道的,无需再次通过命令行输入。 不要通过参数-N进行输入密码,因为不是每个命令都会有-N这个参数,我想知道针对ssh-keygen和ssh-copy-id这样的命令如何进行交互式输入。

问题

通过childprocess.spawn 执行ssh-keygen和ssh-copy-id命令时,每次等到输入密码时,stdout就监听不到数据了。 ssh-keygen命令好像在执行密码的时候,不是在子进程进行输出的。

测试代码

const {
	spawn
} = require('child_process');
const child = spawn('ssh-keygen');

child.stdout.on('data', (data) => {
	let content = data.toString();
	console.log('child.stdout: \r\n'+ data.toString())
	console.log('wirte begin:\r\n')
	if (content.indexOf('Enter file') >= 0) {
		child.stdin.write("id_rsd\r\n");
	} else {
		child.stdin.write("empty\r\n");
	}
	console.log('write end \r\n');
});

打印内容

root[@iZ1193ih9wgZ](/user/iZ1193ih9wgZ):~/test/nssh# node shell.js
child.stdout:
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
wirte begin:

Enter passphrase (empty for no passphrase): write end
4 回复

stdout的data事件貌似只能捕捉到非交互式输出, 你的交互式提示是捕捉不到的. 有个pty.js的库可以做到, 我试了一下, 很完美:

const pty = require('pty.js')

const child = pty.spawn('ssh-keygen')
child.on('data', function (data) {
    console.log(data)
    if (data.includes('Enter file'))
        return child.write('id_rsa\r')
    if (data.includes('Enter passphrase'))
        return child.write('\r')
    if (data.includes('Enter same passphrase'))
        return child.write('\r')
    if (data.includes('Overwrite (y/n)?'))
        return child.write('n\r')
})

@XiaozhongLiu 666,很好的解决方案

试下sshpass。ssh我是试过的,ssh-copy-id没试过。

@Shawn-ye 这个好像只针对ssh这个命令,其他的命令都无法输入

回到顶部