Coder Social home page Coder Social logo

node-netstat's Introduction

node-netstat

A library utility for reading netstat data. It's been tested on Ubuntu 14.04/16.04, Windows 7 and OS X Yosemite.

Installation

node-netstat can be installed via npm:

$ npm install node-netstat

Usage

var netstat = require('node-netstat');

netstat({
	filter: {
		pid: 4123,
		protocol: 'tcp'
	},
	limit: 5
}, function (data) {
    // a single line of data read from netstat
});

API

void netstat(object options, function handler)

Executes a netstat query with any options supplied and executes handler for each line result read from netstat.

The handler signature is void|boolean function(object parsedItem) where parsedItem represents a single result from netstat. A typical parsedItem will look like this:

var item = {
    protocol: String,   // 'tcp', 'udp', or 'tcp6'
    local: {
		port: Number,
		address: String // null if a loopback address
	},
    remote: {
		port: Number,
		address: String // null if a loopback address
	},
    state: '',
    pid: Number         // 0 if it could not be found/parsed
};

If the return value is false, processing will stop and any remaining results will not be parsed.

Options

  • sync - (boolean) execute the operation synchronously.
    • Execution is asynchronous by default.
  • done - (function(error)) node-style callback, executed after the netstat command completed execution or encountered an error`.
  • platform - (string) overrides the platform value returned from os.platform().
  • limit - (number) limits the results read and parsed from the netstat process. Nothingness means no limit.
  • filter - (object) a hash of value conditions for parsed line objects. If a key/value doesn't correspond with one(s) on a parsed object, handler won't get called.
  • watch - (boolean) repeatedly run until processing is cancelled by the line handler or by the external handler.

object netstat.commands

A hash map with command pattern objects:

{
	cmd: 'netstat',
	args: ['-lmnop', '--tcp']
};

The keys in netstat.commands correspond to the standard os.platform() return values ('linux', 'win32').

object netstat.parsers

A hash map of line parse handlers with keys corresponding to os.platform() values.

Line parsers have the following signature:

function (line, callback) {
	// parse line contents
	callback(parsedItem);
}

line is a raw line of output read from netstat. callback is a function and accepts a single argument: the parsed data object.

object netstat.parserFactories

A hash map of the factory functions used to generate the default parsers with keys corresponding to os.platform() values. Some factories include options that may be customized for specific use cases.

Linux

Options
  • parseName - (boolean) parse and include processName in results. Default: false

Common Recipes

Include the process name and allow filtering on it (linux only)
const netstat = require('node-netstat');

netstat.parsers.linux = netstat.parserFactories.linux({
  parseName: true,
});

netstat({}, item => console.log(item));

/* output:
{ protocol: 'tcp',
  local: { port: 631, address: '127.0.0.1' },
  remote: { port: NaN, address: null },
  state: 'LISTEN',
  pid: 0,
  processName: '' }
{ protocol: 'tcp',
  local: { port: 1339, address: '127.0.0.1' },
  remote: { port: NaN, address: null },
  state: 'LISTEN',
  pid: 10474,
  processName: 'node' }
*/

object netstat.filters

A hash map of closure factories to handle logic for certain options. See source for more details on implementations for specific filters.

object netstat.utils

An object with several useful functions for implementing custom parsers.

string netstat.version

The version of node-netstat

Canceling async netstat externally

If the watch option is set, the line handler can never be called. To deal with this scenario, a handler is returned and can be called to cancel netstat watching externally.

const impossibleFilter = {...};
let handler = netstat(impossibleFilter, item => console.log(item));

...

// Some time later we need to finish our script,
// we cancel netsat so
handler.cancel();

Any subsequent call to handler.cancel() takes no effect.

Extensions

node-netstat is highly extensible via the filters, parsers, and commands properties.

Bugs and Feedback

If you see a bug or have a suggestion, feel free to open an issue here.

Contributions

PR's welcome! There are no strict style guidelines, just follow best practices and try to keep with the general look & feel of the code present. All submissions must pass jslint and have a test to verify (if applicable).

License

Unlicense. This is a Public Domain work.

Public Domain

"Make art not law" -Nina Paley

node-netstat's People

Contributors

addisonelliott avatar danielkrainas avatar dirtyhairy avatar eastarctica avatar javascriptdude avatar mnkhouri avatar nick-allen avatar sp9usb avatar xloem avatar yoiang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

node-netstat's Issues

Netstat is not finding a running localhost on MacOS Sonoma

On MacOS Sonoma, a line like
'tcp46 0 0 *.8809 *.* LISTEN ' is not found.
One reason is the command args being ['-v', '-n'], which should be ['-a', '-n'] to find it in the netstat output.
Another reason could be the absence of a pid in this line. When I fit the line in the parser test, there are errors in the code that establishes the pid.
Also the test shows that parsing *.8809 results in port: null, address: null, which is not very informative.

NodeJS v20.11.0
MacOS Sonoma 14.2.1

[Feature Request]: Throw Error if net-tools is not installed

Hello,

node-netstat currently does nothing if the command netstat is not found (i.e. net-tools is not installed). For example:

node-netstat does nothing

code source (click to view)
/**
 * index.js
 */

const netstat = require('node-netstat');
netstat(
  { filter: { protocol: 'tcp' }, limit: 1 },
  (data) => console.log(data)
);

Commands and outputs:

node-netstat$ which netstat
netstat not found
node-netstat$ node index.js 
node-netstat$ sudo pacman -S --noconfirm net-tools
resolving dependencies...
looking for conflicting packages...

Packages (1) net-tools-2.10-2

Total Installed Size:  0.51 MiB

:: Proceed with installation? [Y/n] 
(1/1) checking keys in keyring                                                              [------------------------------------------------------] 100%
(1/1) checking package integrity                                                            [------------------------------------------------------] 100%
(1/1) loading package files                                                                 [------------------------------------------------------] 100%
(1/1) checking for file conflicts                                                           [------------------------------------------------------] 100%
(1/1) checking available disk space                                                         [------------------------------------------------------] 100%
:: Processing package changes...
(1/1) installing net-tools                                                                  [------------------------------------------------------] 100%
:: Running post-transaction hooks...
(1/1) Arming ConditionNeedsUpdate...
node-netstat$ node index.js                       
{
  protocol: 'tcp',
  local: { port: 6600, address: null },
  remote: { port: NaN, address: null },
  state: 'LISTEN',
  pid: 1564
}
node-netstat$ which netstat
/usr/bin/netstat

This can be difficult to debug. On netstat's manual page, we have

Note

This program is obsolete. Replacement for netstat is ss. Replacement for netstat -r is ip route. Replacement for netstat -i is ip -s > link. Replacement for netstat -g is ip maddr.

so it's not uncommon for docker images and linux distributions do not ship with net-tools.

Would it be possible to simply throw an Error with a helpful message telling the user to install net-tools?

Thank you :)).

Name missing

Hello!

I wanted to include node-netstat as opposed to netstat because it gives me a better way of filtering and limiting. However I don't get any names of the programms.

This is what netstat tulpn gives me:

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 192.168.99.10:53        0.0.0.0:*               LISTEN      306/named
tcp        0      0 127.0.0.1:53            0.0.0.0:*               LISTEN      306/named
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
udp        0      0 0.0.0.0:5353            0.0.0.0:*                           364/avahi-daemon: r
udp        0      0 0.0.0.0:40475           0.0.0.0:*                           7618/dhcpd
udp        0      0 192.168.99.10:53        0.0.0.0:*                           306/named
udp        0      0 192.168.3.112:53        0.0.0.0:*                           306/named
udp        0      0 192.168.3.103:53        0.0.0.0:*                           306/named
udp        0      0 10.8.0.34:53            0.0.0.0:*                           306/named
udp        0      0 172.18.0.1:53           0.0.0.0:*                           306/named
udp        0      0 172.17.0.1:53           0.0.0.0:*                           306/named
udp        0      0 127.0.0.1:53            0.0.0.0:*                           306/named
udp        0      0 0.0.0.0:67              0.0.0.0:*                           7618/dhcpd
udp        0      0 0.0.0.0:68              0.0.0.0:*                           7154/dhclient
udp        0      0 0.0.0.0:68              0.0.0.0:*                           7011/dhclient
udp        0      0 0.0.0.0:68              0.0.0.0:*                           6043/dhclient

this is the console output of node-netstat

{ protocol: 'tcp',
  local: { port: 22, address: '192.168.3.103' },
  remote: { port: 49276, address: '192.168.3.109' },
  state: 'ESTABLISHED',
  pid: 0 }
{ protocol: 'tcp',
  local: { port: 41338, address: '192.168.3.103' },
  remote: { port: 443, address: '192.168.3.103' },
  state: 'TIME_WAIT',
  pid: 0 }
{ protocol: 'tcp',
  local: { port: 41300, address: '192.168.3.103' },
  remote: { port: 443, address: '192.168.3.103' },
  state: 'TIME_WAIT',
  pid: 0 }
{ protocol: 'tcp',
  local: { port: 52200, address: '192.168.3.103' },
  remote: { port: 80, address: '192.168.3.103' },
  state: 'TIME_WAIT',
  pid: 0 }
{ protocol: 'tcp',
  local: { port: 52310, address: '192.168.3.103' },
  remote: { port: 80, address: '192.168.3.103' },
  state: 'TIME_WAIT',
  pid: 0 }

Is there any way to include the name also and the other informations? Thank you in advance!

pid filter working?

Hey there,

I am trying to run node-netstat as per the example but not able to run on my system. Rest filter are working. Can anyone help me out with it?

$ npm -v
5.6.0
$ node -v
v8.11.1

data returned

any particular reason the data doesnt return in a standardformat like JSON or just an array? What is this?

{ protocol: 'tcp',
local: { port: 24801, address: '127.0.0.1' },
remote: { port: 49669, address: '127.0.0.1' },
state: 'ESTABLISHED',
pid: 3968 }
{ protocol: 'tcp',
local: { port: 49669, address: '127.0.0.1' },
remote: { port: 24801, address: '127.0.0.1' },
state: 'ESTABLISHED',
pid: 4660 }
{ protocol: 'tcp',
local: { port: 49810, address: '127.0.0.1' },
remote: { port: 49811, address: '127.0.0.1' },
state: 'ESTABLISHED',
pid: 11176 }
{ protocol: 'tcp',
local: { port: 49811, address: '127.0.0.1' },
remote: { port: 49810, address: '127.0.0.1' },
state: 'ESTABLISHED',
pid: 11176 }
{ protocol: 'tcp',
local: { port: 49822, address: '127.0.0.1' },
remote: { port: 49823, address: '127.0.0.1' },
state: 'ESTABLISHED',
pid: 10540 }

Emit event when processing is complete

In order to use your utility programatically, the consumer needs to know when the parsing is complete. I recommend adding to netstat.js::stopParsing() a call to a callback defined by the consumer in options.

For instance calling options.parsingDone().

Thanks for the cool utility.

Netstat options.filter.state - LISTEN vs LISTENING

On Windows, the state for a started HTTP server is LISTENING, but on Linux, it's LISTEN.

Is there a way to consolidate these differences when filtering?

Also, it would be nice if all filter conditions allow for AND/OR operators, or takes an array of possible values to match.

Thank you :).

Handler function not being called

I'm working on an existing codebase and found that the handler function is not being invoked.
I checked previous issues and noticed that one said set sync: true but that didn't work. I'm currently running: node-netstat: "^1.6.0" and trying to use it to close a standalone Selenium Server running a webdriver on port 4444 locally. Code snippet below. Greatly appreciate any advice on ways to fix/refactor. ๐Ÿ™

const netstat = require('node-netstat');
const fkill = require('fkill');

async function getStopWdPromise() {
    return await new Promise((resolve, reject) => {
        netstat({
            sync: true,
            filter: {
                protocol: 'tcp',
                local: {port: 4444, address: null}
            },
            limit: 1,
            done: function (error) {
               console.log(error) // this gets logged error = null
        }
        }, function (data) {
            console.log(data) // everything in this function does not get logged
            console.log(`Killing WebDriver process with pid ${data.pid}`);
            fkill(data.pid, {force: true});
            setTimeout(function () { console.log('Killed WebDriver process') }, 5000);
            resolve();
        });
    });
}

Implement Synchronous behavior

For those who want to write synchronous based applications, could you add functionality to allow your tool synchronously on demand?

Maybe options.sync=true would be the trigger.

Windows async handler never ends

Hi there,

When running the async version of node-netstat on windows (Windows 7 here) the handler never actually ends, I have to add the option 'sync: true' for it to end. A friendly guy on Discord tried to help me find and fix the problem but I'm afraid it has eluded me.

I'm sure it has something to do with emitLines not properly closing the stream but I don't have enough experience with child processes to fix it.

Edit: Let me know if you need more feedback from me! :)

Edit2: Okay so it seems I was chasing a phantom bug which was actually solved through PR #16 (sorry!). The stream you use hooks up to the stdout of node itself, which you keep open for your "watch" option and that sent myself and the friendly Discord guy on a wild goose hunt. With the UDP fix this lib seems to be working for me as intended. Thank you!

Filtering by Port

I am trying to export only the processes running on port 3000. Using the code

netstat({
    filter: {
        protocol: 'tcp',
        local: {port:3000}
    },
    limit: 1
}, function (data) {
    console.log(data)
});

I am using Windows 10. Removing the local: {port: 3000} returns the following results:

{ protocol: 'tcp',
  local: { port: 135, address: null },
  remote: { port: 0, address: null },
  state: 'LISTENING',
  pid: 912 }
{ protocol: 'tcp',
  local: { port: 445, address: null },
  remote: { port: 0, address: null },
  state: 'LISTENING',
  pid: 4 }
{ protocol: 'tcp',
  local: { port: 623, address: null },
  remote: { port: 0, address: null },
  state: 'LISTENING',
  pid: 11628 }
{ protocol: 'tcp',
  local: { port: 1301, address: null },
  remote: { port: 0, address: null },
  state: 'LISTENING',
  pid: 9992 }
{ protocol: 'tcp',
  local: { port: 3000, address: null },
  remote: { port: 0, address: null },
  state: 'LISTENING',
  pid: 8556 }

netstat crash: Cannot read property 'on' of undefined

Hi ! My node application crash with netstat.

the error just occurred, i just reinstalled my server under centos 8, i hit something else, and my application crashed with the following error:

[30minecraft] PID is : 197037
/home/datahosting/new-manager/node_modules/node-netstat/lib/utils.js:68
    stream.on('data', function (data) {
           ^

TypeError: Cannot read property 'on' of undefined
    at exports.emitLines (/home/datahosting/new-manager/node_modules/node-netstat/lib/utils.js:68:12)
    at exports.async (/home/datahosting/new-manager/node_modules/node-netstat/lib/activators.js:48:5)
    at module.exports (/home/datahosting/new-manager/node_modules/node-netstat/lib/netstat.js:65:16)
    at Timeout._onTimeout (/home/datahosting/new-manager/server.js:53:3)
    at ontimeout (timers.js:436:11)
    at tryOnTimeout (timers.js:300:5)
    at listOnTimeout (timers.js:263:5)
    at Timer.processTimers (timers.js:223:10)

My code code:

		netstat({
			filter: {
				pid: game.pid,
				state: 'LISTENING'
			}
		}, item => {
			done: error => {
				if (err) return;
					if (item.local.port != settings.params.port) {
						game.stdin.write(config.games[settings.gameType].stop + '\n');
						fs.appendFile('logs/logs-port-error.log', "\r\n[" + id + "] " + new Date() + ": Port used" + item.local.port + " allow port: " + settings.params.port, 'utf8', (err) => {
						});
					}
					return;
			}
		});

Thank for you help !

wait cmd

Do you guys have a way to run something like 'netstat -w10' with in node-netstat?

Need help : wait for port on 127.0.0.1 till it is in LISTENING mode and get pid

Is it possible to use node-netstat to wait for a port until it is in LISTENING mode.

Actually, I am trying to automate appium start stop process for mobile tests using webdriverio config.

The appium server takes time to start and port to be in listening mode.
If the port is not in listening mode then wdio test runner is not able to connect to it and configurations fails.

So wanted to know if there is anyway I can wait for this port 4723 on 127.0.0.1 and I also want the pid of this port so that I can use windows taskkill /F /PID /T to terminate it once the process is done.

Error Module not found

Hi,
I have the following error:

ERROR in ./node_modules/node-netstat/lib/netstat.js 9:10-31
Module not found: Error: Can't resolve '../package' in 'C:\Users...\node_modules\node-netstat\lib'

If I change '../package' to '../package.json' in line 9 of node_modules/node-netstat/lib/netstat.js it is solved.
Would it be possible to change it? Or do you have any suggestions on how I might solve the problem without having to change files in node_modules?

Thank you in advance!

Return process does not exist message

small suggestion, when am trying to check particular port number process exists or not. if it does not exist return some message. like: {status:'process not found'}

i used this code

netstat({
filter: {
protocol: 'tcp',
local: {port:8080}
},
limit: 1
}, function (data) {
console.log(data)
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.