`

node.js child_process operator( after ssh - cd & ls )

ssh 
阅读更多
[node.js] child_process

ssh 远程连接之后对远程服务器的操作。


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'));
        }
    });
}
 



console:

cd /home/xusongqin/ && ls -lt > ./q.log
==>prefix:[-p 22] 
ssh : null

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics