a program to run remote command in *nix via nodejs
发布于 3年前 作者 philsong 1307 次浏览
#!/usr/bin/env node

//a program to run remote command in *nix
//you can telnet to 8124 port to excute any command
//phil songbohr[@163](/user/163).com, [@http](/user/http)://weibo.com/bocaicfa
//2012.4.13

var net = require('net'),
    util  = require('util'),
    exec = require('child_process').exec

var server = net.createServer(function(c){
    console.log('server connected');
    c.on('end', function() {
        console.log('server disconnected');
    });
    c.write('hello\r\n');
  
    function excutecmd(data){
        var start = +new Date();
        
        var cmdline = data.toString('ascii');

        cmdline=cmdline.replace(/\r\n/g, "");
        
        console.log(cmdline + '|' + cmdline.length + '|' + cmdline.indexOf('\n'));
        cmd = exec(cmdline);

        cmd.stdout.on('data', function (data) {
            console.log('stdout: ' + data);
            c.write(data);
        });

        cmd.stderr.on('data', function (data) {
            if (/^execvp\(\)/.test(data)) {
                console.log('Failed to start child process.');
            }
            console.log('stderr: ' + data);
            c.write(data);
        });

        cmd.on('exit', function (code) {
            var end = + new Date();
            var result = 'end: ' + code + ' escape: ' + (end-start) + 'ms\r\n';
            console.log(result);
            c.write(result);
        });
    }
    
    c.on('data', function(data){
        console.log('recv: ' + data);
        
        excutecmd(data);
    });
});
server.listen(8124);
1 回复

第一次用nodejs,比c爽多了,爽!!

回到顶部