Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* Monitors aggregate bandwith directly from your router via SNMP
Public Domain.
Author: http://joonas.fi/
2014-03-09
Output:
15 kB/s
28 kB/s
8 kB/s
6 kB/s
...
Requires node.js. This script is cross platform.
The only dependency is snmp-native NPM module. To install:
$ npm install snmp-native
You may have to specifically enable SNMP from your router: http://imgur.com/hAzn2hZ
This simply dumps kB/s values, but you can use this to build something fancier.
*/
var snmp = require('snmp-native');
var config = {
routerAddr: '10.10.100.100',
routerSnmpPort: 161, // most likely the right one
readCommunity: 'public', // usually "public". a.k.a. password - rather stupid terminology
pollingIntervalMs: 2500, // interval for measurements [milliseconds]
// there may be multiple entries in the snmp interface table
// if 0 does not work for you, try 1, 2 and so on..
snmpInterfaceIndex: 0
};
// Create a Session with explicit default host, port, and community.
var snmpSession = new snmp.Session({
host: config.routerAddr,
port: config.routerSnmpPort,
community: config.readCommunity
});
// this variable holds previous measurement from SNMP so we can calculate delta for it
var previousMeasurement = null;
var snmpQueryResult = function (err, result){
if (err) {
console.log('error: ' + err);
return;
}
var ifOutOctets = result[config.snmpInterfaceIndex];
// first iteration => store measurement right away as previous
if (previousMeasurement === null) {
previousMeasurement = ifOutOctets;
}
// calculate delta
var delta = {
value: ifOutOctets.value - previousMeasurement.value,
receiveStamp: ifOutOctets.receiveStamp - previousMeasurement.receiveStamp
};
// store current measurement as previous, so next iteration gets delta
previousMeasurement = ifOutOctets;
// cannot compute kbs/sec since receive delta time is zero
if (delta.receiveStamp == 0) {
return;
}
var octetsPerSec = delta.value / delta.receiveStamp * 1000;
var kilobytesPerSec = octetsPerSec / 1024;
console.log(Math.round(kilobytesPerSec) + ' kB/s');
};
// here is the actual business:
// - this function is called every pollingIntervalMs milliseconds
// - it polls the router via SNMP protocol for the variable that holds total inbound octets
// - by calculating deltas for the total and timestamps we can calculate kilobytes/sec
var pollResult = function () {
/* inbound traffic:
.1.3.6.1.2.1.2.2.1.10
.iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifInOctets
outbound traffic:
.1.3.6.1.2.1.2.2.1.16
.iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifOutOctets
*/
snmpSession.getSubtree({
oid: [1, 3, 6, 1, 2, 1, 2, 2, 1, 10]
}, snmpQueryResult);
// schedule us to be executed again
setTimeout(pollResult, config.pollingIntervalMs);
};
// get this shit started
pollResult();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.