raumstatus/node/snmp-mac.js

109 lines
2.7 KiB
JavaScript
Raw Normal View History

2013-10-02 12:04:01 +00:00
var redis = require("redis");
var snmp = require("net-snmp");
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var _u = require("underscore");
2013-10-14 19:26:54 +00:00
var redisprefix = "mac:";
2013-10-02 12:04:01 +00:00
var SnmpMac = function(hostname, community) {
var self = this;
var redisClient = redis.createClient();
var session = snmp.createSession(hostname, community, { version: snmp.Version2c } );
var baseoid = "1.3.6.1.2.1.17.7.1.2.2.1.3";
var regexp = /([0-9]+).([0-9]+).([0-9]+).([0-9]+).([0-9]+).([0-9]+)$/;
var names = [];
redisClient.on("connect", function () {
2013-11-26 12:59:34 +00:00
//redisClient.set(redisprefix + "00:80:a3:91:39:1c","ripe-atlas-probe");
//redisClient.set(redisprefix + "d4:ca:6d:33:cf:79","routerboard");
2013-10-02 12:04:01 +00:00
2015-09-16 13:03:02 +00:00
console.log("SNMP-MAC: connected to redis");
2013-10-02 12:04:01 +00:00
self.emit('ready');
2013-10-14 19:26:54 +00:00
});
redisClient.on('error', function(err) {
console.log("redis error: " + err);
});
2013-10-02 12:04:01 +00:00
function getMacFromOID(oid, callback) {
var matches = regexp.exec(oid);
var mac = "";
if(matches != null) {
for(var i = 1; i < matches.length; i++) {
var num = parseInt(matches[i]);
if(num <= 15) mac += "0";
mac += num.toString(16) + ":";
}
mac = mac.substr(0, mac.length-1);
callback(mac);
}
}
function doneCb(error) {
if (error)
console.error(error.toString ());
self.emit('done', _u.uniq(names));
}
function feedCb(varbinds) {
for (var i = 0; i < varbinds.length; i++) {
if (snmp.isVarbindError(varbinds[i])) {
console.error(snmp.varbindError (varbinds[i]));
} else {
if(varbinds[i].value == "3") { // only valid arp entries
getMacFromOID(varbinds[i].oid, function(mac) {
2013-10-20 22:04:58 +00:00
// console.log(mac);
2013-10-14 19:26:54 +00:00
redisClient.get(redisprefix + mac, function(err, reply) {
2013-10-02 12:04:01 +00:00
if(reply != null) {
if (reply.split('')[0] == '"' && reply.split('')[reply.split('').length] == '"') {
var name = "";
for (var i = 1; i < reply.split('').length - 1; i++){
name += reply.split('')[i]
}
names.push()
} else {
names.push(reply);
}
2013-10-02 12:04:01 +00:00
}
});
});
}
}
}
}
this.poll = function() {
names.length = 0;
session.subtree(baseoid, 20, feedCb, doneCb);
2013-10-14 19:26:54 +00:00
};
2013-10-02 12:04:01 +00:00
this.stop = function() {
redisClient.quit();
2013-10-14 19:26:54 +00:00
};
this.add = function (mac, name, callback) {
redisClient.set(redisprefix + mac, name, function (err) {
if(typeof callback === "function") callback(err);
});
};
this.delete = function(mac, callback) {
redisClient.del(redisprefix + mac, function(err) {
if(typeof callback === "function") callback(err);
});
};
2013-10-02 12:04:01 +00:00
2013-10-14 19:26:54 +00:00
};
2013-10-02 12:04:01 +00:00
util.inherits(SnmpMac, EventEmitter);
module.exports = SnmpMac;