我正在try 使用NodeJS启动到Linux机器的远程ssh会话.我的要求是在同一个ssh会话中一个接一个地运行多个shell命令.目前我正在使用simple-ssh
nPM包,该包有效,但我的要求要求不依赖第三方工具/包.相反,建议我使用child_process
进行远程ssh会话.
以下是使用simple-ssh
包的示例:
var SSH = require("simple-ssh")
var ssh = new SSH({
host: 'remote_host',
user: 'username',
pass: 'password'
});
ssh.exec('pwd', {
out: console.log.bind(console)
})
.exec('ls', {
out: console.log.bind(console)
})
.exec('date', {
out: console.log.bind(console)
})
.start();
以下是我用child_process
try 的一个:
const { spawn } = require('child_process');
const child1 = spawn('sshpass', ['-p', 'password', 'ssh', '-T', '-o', 'StrictHostKeyChecking=no', `'username'@'remote_host'`]);
child1.stdin.write('password\n');
child1.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
child1.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
child1.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
const child2 = spawn('sshpass', ['-p', 'password', 'ssh', '-T', '-o', 'StrictHostKeyChecking=no', `'username'@'remote_host'`]);
child2.stdin.write('password\n');
child2.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
child2.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
child2.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
const child3 = spawn('sshpass', ['-p', 'password', 'ssh', '-T', '-o', 'StrictHostKeyChecking=no', `'username'@'remote_host'`]);
child3.stdin.write('password\n');
child3.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
child3.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
child3.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
此外,如果我按顺序运行这些命令,然后打印输出,我将获得所有命令的单个输出(这是我不想要的):
const { spawn } = require('child_process');
const child = spawn('sshpass', ['-p', 'password', 'ssh', '-T', '-o', 'StrictHostKeyChecking=no', `'username'@'remote_host'`]);
child.stdin.write('pwd\n');
child.stdin.write('ls -al\n');
child.stdin.write('date\n');
child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
child.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
child.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
我的问题是如何在持久会话中将三个ssh命令与child_process
spawn
链接起来,并一个接一个地同步运行这些命令?