[size=large][node.js] [b]child_process [/b][/size]
[b]ssh 远程连接之后对远程服务器的操作。[/b]
[color=red][b]console:[/b][/color]
[b]ssh 远程连接之后对远程服务器的操作。[/b]
var cp = require('child_process');
var cmd = 'cd /home/xusongqin/ ls -lt > ./q.log';
console.log(cmd);
spawnProcess('ssh',['-p 10086','xusongqin@192.168.1.123',cmd],function(obj){
console.log('ssh : ' + JSON.stringify(obj));
});
function spawnProcess(command, options, callback) {
var child = null;
if (!!options[0]) {
child = cp.spawn(command, options);
} else {
child = cp.exec(command, options);
}
var prefix = command === 'ssh' ? '[' + options[0] + '] ' : '';
console.log('==>>> prefix:' + prefix);
child.stderr.on('data', function (chunk) {
console.log(addBeauty(chunk));
});
var res = [];
child.stdout.on('data', function (chunk) {
res.push(chunk.toString());
console.log(addBeauty(chunk));
});
function addBeauty(buf) {
return prefix + buf
.toString()
.replace(/\s+$/, '')
.replace(/\n/g, '\n' + prefix);
}
child.on('exit', function (code) {
if (callback) {
callback(code === 0 ? null : code, res && res.join('\n'));
}
});
}
[color=red][b]console:[/b][/color]
cd /home/xusongqin/ && ls -lt > ./q.log
==>prefix:[-p 22]
ssh : null