Skip to content

Instantly share code, notes, and snippets.

@katanacrimson
Created October 24, 2012 22:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save katanacrimson/3949354 to your computer and use it in GitHub Desktop.
Save katanacrimson/3949354 to your computer and use it in GitHub Desktop.
Quickie node.js to grab & parse current local TCP connections [netstat, Windows]
var child = require('child_process'),
util = require('util'),
netstat = child.spawn('netstat', ['-nb']),
out = ''
netstat.stdout.on('data', function(data) {
out += data
})
netstat.stderr.on('data', function(data) {
console.log('err: ' + data)
})
netstat.on('exit', function(code) {
var i, bucket = [], processes = {}
if(code !== 0) {
console.log('!!! exited, status code: ' + code)
return
}
// parse & serialize netstat output
out = out.split(/\n/)
// drop the first three lines...
for(i = 0; i <= 3; i++) out.shift()
out.forEach(function(entry) {
if(!entry) return
entry = entry.replace(/^\s\s*/, '').replace(/\r/, '').replace('Can not obtain ownership information', '[???]').split(/[ ]+/)
if(entry[0][0] == '[') {
i = entry[0].replace(/^\[([^\]]+)\]$/, '$1')
if(processes[i] === undefined) processes[i] = []
processes[i] = processes[i].concat(bucket)
bucket = []
} else {
bucket.push({
conntype:entry[0],
source:entry[1],
dest:entry[2],
//status:entry[3],
})
}
})
out = JSON.stringify(processes)
// READY FOR DISPATCH! *salute*
})
@katanacrimson
Copy link
Author

Justification - I'm creating a remote console to check up on remote lab systems as there's someone getting up to no good (they're playing games on equipment they don't own), yet I don't have any tools to see the ports in use remotely nor the authority to just shut their system down.

Combined with an express.js microserver... ^^;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment