使用Nodejs查找连接到端口的IP数

时间:2014-07-09 19:33:08

标签: javascript node.js networking tcp

以下命令告诉您哪些IP地址连接到端口1234以及每个IP地址的连接数。

netstat -plan|grep :1234|awk {'print $5'}|cut -d: -f 1|sort|uniq -c|sort -nk 1

结果

1 0.0.0.0
1 107.123.93.244
1 107.123.141.5
1 107.123.228.217
1 108.123.198.185
1 109.123.142.131

我们如何从Node.js中收集相同的信息?

1 个答案:

答案 0 :(得分:0)

您可以通过节点child_process module执行命令。例如,使用spawn function可以将命令串起来(意味着将一个命令的输出传递给另一个命令输入)。你的命令有很多管道,但作为文档中的一个例子,这里是你如何运行ps ax | grep ssh

var spawn = require('child_process').spawn,
    ps    = spawn('ps', ['ax']),
    grep  = spawn('grep', ['ssh']);

ps.stdout.on('data', function (data) {
  grep.stdin.write(data);
});

ps.stderr.on('data', function (data) {
  console.log('ps stderr: ' + data);
});

ps.on('close', function (code) {
  if (code !== 0) {
    console.log('ps process exited with code ' + code);
  }
  grep.stdin.end();
});

grep.stdout.on('data', function (data) {
  console.log('' + data);
});

grep.stderr.on('data', function (data) {
  console.log('grep stderr: ' + data);
});

grep.on('close', function (code) {
  if (code !== 0) {
    console.log('grep process exited with code ' + code);
  }
});

关于你的下一个问题:

  

可以捕获命令的输出并将其放入对象/数组吗?

当您获得最后一个命令的数据时(因为您将每个命令的stdout发送到下一个命令的stdin),您可以解析该字符串以获取各行文本。例如:

var os = require("os");

finalCommand.stdout.on("data", function(data) {
    // convert all the output to a single string
    var output = data.toString();

    // split the output by line
    output = output.split(os.EOL);

    // parse each line... etc...
    for (var i = 0; i < output.length; i++) {
        // output for example...
        console.log(output[i]);

        // etc...
    }
});

希望这能让您了解如何将命令串在一起,并在命令完成后解析输出。这有帮助吗?

相关问题