【问题标题】:Find the number of IPs connected to a port using Nodejs使用 Nodejs 查找连接到端口的 IP 数量
【发布时间】:2014-08-30 23:44:00
【问题描述】:

以下命令告诉您哪些 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 中收集相同的信息?

【问题讨论】:

  • Node.js 不是管理工具的替代品,为什么不使用已有的工具呢?如果您坚持,请查看此模块:npmjs.org/package/netstat。另请注意:“您将需要安装 netstat,这不是 netstat 的替代品;只是一个包装器。在大多数类似 unix 的系统上,它应该由 net-tools 包默认提供。”
  • @alandarev 我想要一个方便的页面来显示连接到 10 个不同端口的 IP 地址,因此让节点在网页上显示它比运行 unix 命令 10 次并尝试制作更好数据感。是否可以捕获命令的输出并将其粘贴到对象/数组中?

标签: javascript node.js networking tcp


【解决方案1】:

您可以通过节点的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...
    }
});

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2012-10-26
    相关资源
    最近更新 更多