关于javascript:nodenetsnmp模块手册

24次阅读

共计 42209 个字符,预计需要花费 106 分钟才能阅读完成。

net-snmp

本模块实现了简略网络管理协定 (SNMP) 的 1、2c 和 3 版本。

该模块应用 node package manager (npm)装置。

npm install net-snmp 

It is loaded using the require() function:

var snmp = require ("net-snmp"); 

而后能够创立到近程主机的会话,并用于执行 SNMP 申请和发送 SNMP 陷阱或告诉。

var session = snmp.createSession ("127.0.0.1", "public");

var oids = ["1.3.6.1.2.1.1.5.0", "1.3.6.1.2.1.1.6.0"];

session.get (oids, function (error, varbinds) {if (error) {console.error (error);
    } else {for (var i = 0; i < varbinds.length; i++)
            if (snmp.isVarbindError (varbinds[i]))
                console.error (snmp.varbindError (varbinds[i]))
            else
                console.log (varbinds[i].oid + "=" + varbinds[i].value);
    }
    session.close ();});

session.trap (snmp.TrapType.LinkDown, function (error) {if (error)
        console.error (error);
}); 

[](https://www.npmjs.com/package…

RFC 3413 describes five types of SNMP applications:

  1. 命令生成器应用程序 – 发动读写申请
  2. 命令应答器应用程序 – 对收到的读或写申请作出反应。
  3. 告诉发起者应用程序 — — 产生告诉(陷阱或告诉)。
  4. 接管告诉的应用程序 — — 接管告诉(陷阱或告诉)。
  5. 代理转发利用 – 转发 SNMP 信息。

[](https://www.npmjs.com/package… This Module: Command & Notification Generator

该库提供了一个 Session 类,为建设 “ 命令生成器 “ 和 “ 告诉发起者 “SNMP 应用程序提供反对。

所有的 SNMP 申请都是应用 Session 类的实例进行的。本模块输入两个函数,用于创立 Session 类的实例。

  • createSession() – for v1 and v2c sessions
  • createV3Session() – for v3 sessions

[](https://www.npmjs.com/package… ([target], [community], [options])

createSession()函数实例化并返回一个 SNMPv1 或 SNMPv2c 的 Session 类实例。

// Default options
var options = {
    port: 161,
    retries: 1,
    timeout: 5000,
    backoff: 1.0,
    transport: "udp4",
    trapPort: 162,
    version: snmp.Version1,
    backwardsGetNexts: true,
    idBitsSize: 32
};

var session = snmp.createSession ("127.0.0.1", "public", options); 

可选的 target 参数默认为 127.0.0.1。可选的 “community “ 参数默认为 “public”。可选的options 参数是一个对象,能够蕴含以下我的项目。

  • port – 发送申请的 UDP 端口,默认为161
  • “reties” — — 从新发送申请的次数,默认为 “1”。
  • sourceAddress—-SNMP 申请应来自的 IP 地址,该选项没有默认值,操作系统将在发送 SNMP 申请时抉择一个适当的源地址。
  • sourcePort – UDP 端口,SNMP 申请应从该端口收回,默认为操作系统抉择的短暂端口。
  • timeout — — 在从新尝试或失败之前期待响应的毫秒数,默认值为5000
  • “backoff” — — 每次重试时减少 “ 超时 “ 的系数,不减少时默认为 “1”。
  • transport — — 指定要应用的传输,能够是 udp4udp6,默认为udp4
  • trapPort — — 发送陷阱和告诉的 UDP 端口,默认值为162
  • versionsnmp.Version1snmp.Version2c,默认为snmp.Version1
  • “backwardsGetNexts”—- 容许进行 GetNext 操作的布尔值,以检索词法上在前的 OIDs。
  • idBitsSize1632,默认为32。用来缩小生成的 id 的大小,以便与一些旧设施兼容。

当一个会话完结后,应该敞开它。

session.close (); 

[](https://www.npmjs.com/package… (target, user, [options])

createV3Session()函数实例化并返回一个与 createSession() 雷同的 Session 类实例,只是为 SNMPv3 进行了初始化。

// Default options for v3
var options = {
    port: 161,
    retries: 1,
    timeout: 5000,
    transport: "udp4",
    trapPort: 162,
    version: snmp.Version3,
    idBitsSize: 32,
    context: ""
};

// Example user
var user = {
    name: "blinkybill",
    level: snmp.SecurityLevel.authPriv,
    authProtocol: snmp.AuthProtocols.sha,
    authKey: "madeahash",
    privProtocol: snmp.PrivProtocols.des,
    privKey: "privycouncil"
};

var session = snmp.createV3Session ("127.0.0.1", user, options); 

targetuser 参数是强制性的。可选的 “options “ 参数与 “createSession() “ 调用的含意雷同。选项参数中一个额定的字段是 context 字段,它为会话增加一个 SNMPv3 上下文。

user对象必须蕴含 namelevel字段。level字段能够从 snmp.SecurityLevel 对象中取值。

  • snmp.SecurityLevel.noAuthNoPriv – 不进行音讯认证或加密。
  • snmp.SecurityLevel.authNoPriv — — 用于信息认证,不进行加密。
  • snmp.SecurityLevel.authPriv — — 用于信息认证和加密。

这些字段的含意合乎 RFC3414 的规定。如果提供的 “level “ 是 “authNoPriv “ 或 “authPriv”,那么 “authProtocol “ 和 “authKey “ 字段也必须存在。authProtocol字段能够从 snmp.AuthProtocols 对象中取值。

  • snmp.AuthProtocols.md5 – 用于 MD5 音讯认证。
  • `snmp.AuthProtocols.sha’ — — 用于 SHA 信息认证。

如果提供的 “level “ 是 “authPriv”,那么 “privProtocol “ 和 “privKey “ 字段也必须存在。privProtocol字段能够从 snmp.PrivProtocols 对象中取值。

  • snmp.PrivProtocols.des – 用于 DES 加密。
  • `snmp.PrivProtocols.aes’ — — 用于 AES 加密。

一旦创立了 v3 会话,就能够应用与 v1 和 v2c 雷同的一组 “ 会话 “ 办法。

[](https://www.npmjs.com/package… (“close”, callback)

当会话的底层 UDP 套接字被敞开时,会话会收回 “close “ 事件。

没有参数传递给回调。

在该事件收回之前,所有未实现的申请都会被勾销,导致每个未实现的申请失败。传回给每个申请的谬误将是一个 Error 类的实例,其谬误 message 属性设置为Socket forcibly closed

上面的例子是当一个会话的底层 UDP 套接字被敞开时,打印一条音讯到控制台。

session.on ("close", function () {console.log ("socket closed");
}); 

[](https://www.npmjs.com/package… (“error”, callback)

当会话的底层 UDP 套接字收回谬误时,会话会收回 “error “ 事件。

以下参数将被传递给 “ 回调 “ 函数。

  • errorError类的一个实例,裸露的 message 属性将蕴含一个具体的错误信息。

上面的例子是当一个会话的底层 UDP 套接字产生谬误时,打印一条音讯到控制台,而后敞开该会话。

session.on ("error", function (error) {console.log (error.toString ());
    session.close ();}); 

[](https://www.npmjs.com/package… ()

close()办法敞开 UDP 套接字的底层会话。这将导致会话底层 UDP 套接字收回 “close “ 事件,并传递给会话,导致会话也收回 “close “ 事件。

上面的例子敞开了一个 UDP 套接字底层会话。

session.close (); 

[](https://www.npmjs.com/package… (oids, callback)

get()办法获取一个或多个 OID 的值。

oids参数是一个 OID 字符串数组。一旦申请实现,callback函数就会被调用。以下参数将被传递给 callback 函数。

  • errorError类或子类的实例,如果没有产生谬误,则为null
  • varbinds – varbinds 数组,如果产生谬误将不提供。

varbinds数组中地位 N 的 varbind 将对应于申请中 oids 数组中地位 N 的 OID。

当应用 SNMP 版本 2c 时,必须应用 snmp.isVarbindError() 函数查看每个 varbind 是否存在谬误条件。

以下示例获取 sysName(1.3.6.1.2.1.1.5.0)和 sysLocation(1.3.6.1.2.1.1.6.0)OIDs 的值。

var oids = ["1.3.6.1.2.1.1.5.0", "1.3.6.1.2.1.1.6.0"];

session.get (oids, function (error, varbinds) {if (error) {console.error (error.toString ());
    } else {for (var i = 0; i < varbinds.length; i++) {
            // for version 1 we can assume all OIDs were successful
            console.log (varbinds[i].oid + "|" + varbinds[i].value);
        
            // for version 2c we must check each OID for an error condition
            if (snmp.isVarbindError (varbinds[i]))
                console.error (snmp.varbindError (varbinds[i]));
            else
                console.log (varbinds[i].oid + "|" + varbinds[i].value);
        }
    }
}); 

[](https://www.npmjs.com/package… (oids, [nonRepeaters], [maxRepetitions], callback)

getBulk()办法获取 MIB 树中一个或多个 OID 后按词法排列的 OID 的值。

oids参数是一个 OID 字符串的数组。可选的 nonRepeaters 参数指定 oids 参数中只应返回 1 个 varbind 的 OID 的数量,默认为 0。对于oids 参数中残余的每一个 OID,可选的 maxRepetitions 参数指定了一个 OID 前面的词法 OID 的数量,对于这些 OID,varbind 应该被获取,默认值为20

一旦申请实现,callback函数就会被调用。以下参数将被传递给 callback 函数。

  • errorError类或子类的实例,如果没有产生谬误,则为null
  • varbinds – varbinds 数组,如果产生谬误将不提供。

varbinds数组中 N 地位的 varbind 将与申请中 oids 数组中 N 地位的 OID 绝对应。

对于 varbinds 中的第一个 nonRepeaters 我的项目,每个我的项目将是一个繁多的 varbind。对于 varbinds 中所有残余的我的项目,每个我的项目将是一个 varbinds 数组 – 这使得将响应的 varbinds 与申请的 OID 绑定起来很容易,因为响应的 varbinds 被分组并放在 varbinds 中的雷同地位。

当应用 SNMP 版本 2c 时,必须应用 snmp.isVarbindError() 函数查看每个 varbind 是否存在谬误条件。

上面的例子获取 sysContact(1.3.6.1.2.1.4.0)和 sysName(1.3.6.1.2.1.5. 0)OID,以及 ifTable(1.3.6.1.2.1.2.1.2)表中 ifDescr(1.3.6.1.2.1.2.1.2)和 ifType(1.3.6.1.2.1.2.1.3)列中最多前 20 个 OID。

var oids = [
    "1.3.6.1.2.1.1.4.0",
    "1.3.6.1.2.1.1.5.0",
    "1.3.6.1.2.1.2.2.1.2",
    "1.3.6.1.2.1.2.2.1.3"
];

var nonRepeaters = 2;

session.getNext (oids, nonRepeaters, function (error, varbinds) {if (error) {console.error (error.toString ());
    } else {
        // step through the non-repeaters which are single varbinds
        for (var i = 0; i < nonRepeaters; i++) {if (i >= varbinds.length)
                break;

            if (snmp.isVarbindError (varbinds[i]))
                console.error (snmp.varbindError (varbinds[i]));
            else
                console.log (varbinds[i].oid + "|" + varbinds[i].value);
        }

        // then step through the repeaters which are varbind arrays
        for (var i = nonRepeaters; i < varbinds.length; i++) {for (var j = 0; j < varbinds[i].length; j++) {if (snmp.isVarbindError (varbinds[i][j]))
                    console.error (snmp.varbindError (varbinds[i][j]));
                else
                    console.log (varbinds[i][j].oid + "|"
                            + varbinds[i][j].value);
            }
    }
}); 

[](https://www.npmjs.com/package… (oids, callback)

getNext()办法获取 MIB 树中一个或多个 OID 后按词法排列的 OID 的值。

oids参数是一个 OID 字符串的数组。一旦申请实现,就会调用 callback 函数。以下参数将被传递给 callback 函数。

  • errorError类或子类的实例,如果没有产生谬误,则为null
  • varbinds – varbinds 数组,如果产生谬误将不提供。

varbinds数组中地位 N 的 varbind 将对应于申请中 oids 数组中地位 N 的 OID。

当应用 SNMP 版本 2c 时,必须应用 snmp.isVarbindError() 函数查看每个 varbind 是否存在谬误条件。

上面的例子获取 sysObjectID(1.3.6.1.1.2.1.1.0)和 sysName(1.3.6.1.1.2.1.4.0)OID 之后的下一个 OID 的值。

var oids = [
    "1.3.6.1.2.1.1.1.0",
    "1.3.6.1.2.1.1.4.0"
];

session.getNext (oids, function (error, varbinds) {if (error) {console.error (error.toString ());
    } else {for (var i = 0; i < varbinds.length; i++) {
            // for version 1 we can assume all OIDs were successful
            console.log (varbinds[i].oid + "|" + varbinds[i].value);
        
            // for version 2c we must check each OID for an error condition
            if (snmp.isVarbindError (varbinds[i]))
                console.error (snmp.varbindError (varbinds[i]));
            else
                console.log (varbinds[i].oid + "|" + varbinds[i].value);
        }
    }
}); 

session.inform (typeOrOid, [varbinds], [options], callback)

inform()办法发送一个 SNMP 信息。

typeOrOid参数能够是两种类型之一:snmp.TrapType对象中定义的常量之一(不包含 snmp.TrapType.EnterpriseSpecific 常量),或者是一个 OID 字符串。

在申请音讯中搁置的第一个 varbind 将是 sysUptime.0 OID(1.3.6.1.2.1.1.3.0)。这个 varbind 的值将是process.uptime() 函数返回的值乘以 100(这能够通过在可选的 options 参数中提供 upTime 来笼罩,如下文所述)。

这之后会有第二个 varbind 的 snmpTrapOID.0 OID (1.3.6.1.6.3.1.1.4.1.0)。这个值取决于typeOrOid 参数。如果指定了一个常量,那么常量的陷阱 OID 将被用来作为 varbinds 的值,否则指定的 OID 字符串将被用来作为 varbind 的值。

可选的 “varbinds “ 参数是要蕴含在信息申请中的 varbinds 数组,默认为空数组[]

可选的 options 参数是一个对象,能够蕴含以下我的项目。

  • upTime – inform 中 sysUptime.0 OID(1.3.6.1.2.1.1.3.0) 的值,默认为 process.uptime() 函数返回的值乘以 100。

一旦收到对信息申请的回答或产生谬误,就会调用 “ 回调 “ 函数。以下参数将被传递给 callback 函数。

  • errorError类或子类的实例,如果没有产生谬误,则为null
  • varbinds – varbinds 数组,如果产生谬误将不提供。

varbinds数组中 N 地位的 varbind 将与申请中 varbinds 数组中 N 地位的 varbind 绝对应。近程主机应该依照申请中的指定回传 varbinds 和它们的值,varbinds数组将蕴含近程主机发回的每个 varbind。

通常没有理由应用 varbinds 参数的内容,因为 varbinds 是在申请中发送的。

上面的例子发送了一个通用的冷启动信息给近程主机,它不蕴含任何 varbinds。

session.inform (snmp.TrapType.ColdStart, function (error) {if (error)
        console.error (error);
}); 

上面的例子是向近程主机发送一个企业特定的信息,并蕴含两个企业特定的 varbinds。

var informOid = "1.3.6.1.4.1.2000.1";

var varbinds = [
    {
        oid: "1.3.6.1.4.1.2000.2",
        type: snmp.ObjectType.OctetString,
        value: "Periodic hardware self-check"
    },
    {
        oid: "1.3.6.1.4.1.2000.3",
        type: snmp.ObjectType.OctetString,
        value: "hardware-ok"
    }
];

// Override sysUpTime, specfiying it as 10 seconds...
var options = {upTime: 1000};
session.inform (informOid, varbinds, options, function (error) {if (error)
        console.error (error);
}); 

session.set (varbinds, callback)

set()办法设置一个或多个 OID 的值。

varbinds参数是一个 varbind 对象的数组。一旦申请实现,就会调用 callback 函数。以下参数将被传递给 callback 函数。

  • errorError类或子类的实例,如果没有产生谬误,则为null
  • varbinds – varbinds 数组,如果产生谬误将不提供。

varbinds数组中 N 地位的 varbind 将与申请中 varbinds 数组中 N 地位的 varbind 绝对应。除非产生谬误,否则近程主机应该依照申请中指定的 varbinds 和它们的值回传。varbinds数组将蕴含近程主机发回的每个 varbind。

当应用 SNMP 版本 2c 时,必须应用 snmp.isVarbindError() 函数查看每个 varbind 是否存在谬误条件。

上面的例子设置了 sysName(1.3.6.1.2.1.1.4.0)和 sysLocation(1.3.6.1.2.1.1.6.0)OID 的值。

var varbinds = [
    {
        oid: "1.3.6.1.2.1.1.5.0",
        type: snmp.ObjectType.OctetString,
        value: "host1"
    }, {
        oid: "1.3.6.1.2.1.1.6.0",
        type: snmp.ObjectType.OctetString,
        value: "somewhere"
    }
];

session.set (varbinds, function (error, varbinds) {if (error) {console.error (error.toString ());
    } else {for (var i = 0; i < varbinds.length; i++) {
            // for version 1 we can assume all OIDs were successful
            console.log (varbinds[i].oid + "|" + varbinds[i].value);
        
            // for version 2c we must check each OID for an error condition
            if (snmp.isVarbindError (varbinds[i]))
                console.error (snmp.varbindError (varbinds[i]));
            else
                console.log (varbinds[i].oid + "|" + varbinds[i].value);
        }
    }
}); 

session.subtree (oid, [maxRepetitions], feedCallback, doneCallback)

subtree()办法获取 MIB 树中以指定的 OID 为根底,按词法排列在指定 OID 之后的所有 OID 的值。例如,sysName(1.3.6.1.2.1.1.5.0)和 sysLocation(1.3.6.1.2.1.1.6.0)这两个 OID 都有雷同的基零碎(1.3.6.1.2.1.1)OID。

对于 SNMP 版本 1,反复调用get(),直到返回的一个 OID 不应用指定的 OID 作为其根底。对于 SNMP 版本 2c,反复调用getBulk(),直到返回的 OIDs 中没有应用指定的 OID 作为其根底。

oid参数是一个 OID 字符串。当应用 SNMP 版本 2c 时,可选的 maxRepetitions 参数被传递给 getBulk() 申请。

一旦获取了所有的 OID 值,这个办法将不会调用一个回调。相同,feedCallback函数将在每次从近程主机收到响应时被调用。以下参数将被传递给 feedCallback 函数。

  • varbinds – varbinds 数组,至多蕴含一个 varbind。

当应用 SNMP 版本 2c 时,必须应用 snmp.isVarbindError() 函数查看每个 varbind 是否存在谬误条件。

一旦返回的 OID 中至多有一个没有应用指定的 OID 作为其根底,或者产生了谬误,doneCallback函数将被调用。以下参数将被传递给 doneCallback 函数。

  • errorError类或子类的实例,如果没有产生谬误,则为null

一旦 doneCallback 函数被调用,申请就实现了,feedCallback函数将不再被调用。

如果 feedCallback 函数调用时返回 true 值,则不再调用 get()getBulk()办法,调用doneCallback

上面的例子是获取零碎(1.3.6.1.2.1.1)下的所有 OID。

var oid = "1.3.6.1.2.1.1";

function doneCb (error) {if (error)
        console.error (error.toString ());
}

function feedCb (varbinds) {for (var i = 0; i < varbinds.length; i++) {if (snmp.isVarbindError (varbinds[i]))
            console.error (snmp.varbindError (varbinds[i]));
        else
            console.log (varbinds[i].oid + "|" + varbinds[i].value);
    }
}

var maxRepetitions = 20;

// The maxRepetitions argument is optional, and will be ignored unless using
// SNMP verison 2c
session.subtree (oid, maxRepetitions, feedCb, doneCb); 

session.table (oid, [maxRepetitions], callback)

table()办法获取 MIB 树中以指定的 OID 为根底的、按词法排列在指定 OID 之后的所有 OID 的值,这与 subtree() 办法很类似。

这个办法被设计用来获取概念表,例如 ifTable(1.3.6.1.2.1.2.2)表。返回的 varbinds 的值将被结构化为代表概念行的对象。而后将每一行放入一个对象中,行的索引是键,例如:

var table = {// Rows keyed by ifIndex (1 and 2 are shown)
    1: {// ifDescr (column 2) and ifType (columnd 3) are shown
        2: "interface-1",
        3: 6,
        ...
    },
    2: {
        2: "interface-2",
        3: 6,
        ...
    },
    ...
} 

本办法外部调用 subtree() 办法来获取指定表的子树。

oid参数是一个 OID 字符串。如果传递的 OID 字符串不代表一个表,那么产生的用于保留表数据的对象将是空的,也就是说,它将不蕴含索引和行。可选的 maxRepetitions 参数被传递给 subtree() 申请。

一旦整个表被获取,callback函数将被调用。以下参数将被传递给 callback 函数。

  • errorError类或子类的实例,如果没有产生谬误,则为null
  • table — — 蕴含对象援用,代表按索引键入的概念行(例如,ifTable 表的行按 ifIndex 键入),每个行对象将蕴含按列号键入的值,如果产生谬误将不提供。

如果 subtree() 返回的任何 varbind 产生谬误,将不会向 callback 函数传递任何表。失败的起因和相干的 OID 字符串(从调用 snmp.varbindError() 函数返回的),将作为 RequestFailedError 类的一个实例,在 error 参数中传递给 callback 函数。

上面的例子获取 ifTable(1.3.6.1.2.1.2.2)表。

var oid = "1.3.6.1.2.1.2.2";

function sortInt (a, b) {if (a > b)
        return 1;
    else if (b > a)
        return -1;
    else
        return 0;
}

function responseCb (error, table) {if (error) {console.error (error.toString ());
    } else {
        // This code is purely used to print rows out in index order,
        // ifIndex's are integers so we'll sort them numerically using
        // the sortInt() function above
        var indexes = [];
        for (index in table)
            indexes.push (parseInt (index));
        indexes.sort (sortInt);
        
        // Use the sorted indexes we've calculated to walk through each
        // row in order
        for (var i = 0; i < indexes.length; i++) {
            // Like indexes we sort by column, so use the same trick here,
            // some rows may not have the same columns as other rows, so
            // we calculate this per row
            var columns = [];
            for (column in table[indexes[i]])
                columns.push (parseInt (column));
            columns.sort (sortInt);
            
            // Print index, then each column indented under the index
            console.log ("row for index =" + indexes[i]);
            for (var j = 0; j < columns.length; j++) {console.log ("column" + columns[j] + "="
                        + table[indexes[i]][columns[j]]);
            }
        }
    }
}

var maxRepetitions = 20;

// The maxRepetitions argument is optional, and will be ignored unless using
// SNMP verison 2c
session.table (oid, maxRepetitions, responseCb); 

session.tableColumns (oid, columns, [maxRepetitions], callback)

tableColumns()办法实现了与 table() 办法雷同的接口。然而,只有在 columns 参数中指定的列才会呈现在生成的表中。

当只须要选定的列时,应该应用这个办法,并且会比 table() 办法快很多倍,因为会影响更少的数据量。

上面的例子是获取 ifTable(1.3.6.1.2.1.2.2)表,并指定只获取 ifDescr(1.3.6.1.2.1.2.1.2)和 ifPhysAddress(1.3.6.1.2.1.2.1.6)列。

var oid = "1.3.6.1.2.1.2.2";
var columns = [2, 6];

function sortInt (a, b) {if (a > b)
        return 1;
    else if (b > a)
        return -1;
    else
        return 0;
}

function responseCb (error, table) {if (error) {console.error (error.toString ());
    } else {
        // This code is purely used to print rows out in index order,
        // ifIndex's are integers so we'll sort them numerically using
        // the sortInt() function above
        var indexes = [];
        for (index in table)
            indexes.push (parseInt (index));
        indexes.sort (sortInt);
        
        // Use the sorted indexes we've calculated to walk through each
        // row in order
        for (var i = 0; i < indexes.length; i++) {
            // Like indexes we sort by column, so use the same trick here,
            // some rows may not have the same columns as other rows, so
            // we calculate this per row
            var columns = [];
            for (column in table[indexes[i]])
                columns.push (parseInt (column));
            columns.sort (sortInt);
            
            // Print index, then each column indented under the index
            console.log ("row for index =" + indexes[i]);
            for (var j = 0; j < columns.length; j++) {console.log ("column" + columns[j] + "="
                        + table[indexes[i]][columns[j]]);
            }
        }
    }
}

var maxRepetitions = 20;

// The maxRepetitions argument is optional, and will be ignored unless using
// SNMP verison 2c
session.tableColumns (oid, columns, maxRepetitions, responseCb); 

session.trap (typeOrOid, [varbinds], [agentAddrOrOptions], callback)

trap()办法发送一个 SNMP trap.typeOrOid` 参数能够是两种类型之一。

typeOrOid参数能够是两种类型之一:snmp.TrapType对象中定义的常量之一(不包含 snmp.TrapType.EnterpriseSpecific 常量),或者一个 OID 字符串。

对于 SNMP 版本 1,当指定常量时,陷阱中会设置以下字段。

  • 企业字段设置为 OID1.3.6.1.4.1
  • 企业字段设置为 OID1.3.6.1.4.1
  • 特定陷阱字段设置为 0。

当指定了 OID 字符串时,会在陷阱中设置以下字段。

  • 从 OID 字符串中去掉最初的小数点,并设置在特定的陷阱字段中。
  • 其余的 OID 字符串在企业畛域设置。
  • generic-trap 字段设置为常数snmp.TrapType.EnterpriseSpecific

在这两种状况下,陷阱 PDU 中的工夫戳字段被设置为 process.uptime() 函数返回的值乘以100

SNMP 版本 2c 的音讯与版本 1 相比有很大不同。2c 版陷阱的格局要简略得多,只是一个 varbinds 的序列。陷阱音讯中的第一个 varbind 是 sysUptime.0 的 OID(1.3.6.1.6.3.1.1.4.1.0)。这个 varbind 的值将是 process.uptime() 函数返回的值乘以 100(能够通过在可选的 options 参数中提供 upTime 来笼罩,如下文所述)。

这之后会有第二个 varbind 的 snmpTrapOID.0 OID (1.3.6.1.6.3.1.1.4.1.0)。这个值取决于typeOrOid 参数。如果指定了一个常量,那么常量的陷阱 OID 将被用来作为 varbinds 的值,否则指定的 OID 字符串将被用来作为 varbind 的值。

可选的 varbinds 参数是要蕴含在陷阱中的 varbinds 数组,默认为空数组[]

可选的 agentAddrOrOptions 参数能够是两种类型之一,一种是用于填充 SNMP 版本 1 类型陷阱的 agent-addr 字段的 IP 地址,默认为127.0.0.1,或者是一个对象,能够蕴含以下我的项目。

  • agentAddr – 用于填充 SNMP 版本 1 类型陷阱的代理地址字段的 IP 地址,默认值为127.0.0.1
  • upTime – trap 中 sysUptime.0 OID(1.3.6.1.6.3.1.4.1.0) 的值,默认为 process.uptime() 函数返回的值乘以 100。

留神 当应用 SNMP 版本 2c 时,如果指定了 agentAddr 参数,则会被疏忽,因为版本 2c 的陷阱信息没有 agent-addr 字段。

一旦陷阱被发送或产生谬误,”callback “ 函数将被调用。以下参数将被传递给 callback 函数。

  • errorError类或子类的实例,如果没有产生谬误,则为null

以下示例应用 SNMP 版本 1 的陷阱向近程主机发送企业特定的陷阱,并在陷阱中蕴含 sysName(1.3.6.1.2.1.1.5.0)varbind。在发送 trap 之前,agentAddr字段应用 DNS 计算出本地主机的主机名。

var enterpriseOid = "1.3.6.1.4.1.2000.1"; // made up, but it may be valid

var varbinds = [
    {
        oid: "1.3.6.1.2.1.1.5.0",
        type: snmp.ObjectType.OctetString,
        value: "host1"
    }
];

dns.lookup (os.hostname (), function (error, agentAddress) {if (error) {console.error (error);
    } else {
        // Override sysUpTime, specfiying it as 10 seconds...
        var options = {agentAddr: agentAddress, upTime: 1000};
        session.trap (enterpriseOid, varbinds, agentAddress,
                function (error) {if (error)
                console.error (error);
        });
    }
}); 

上面的例子应用 SNMP 版本 1 的 trap 向近程主机发送一个通用的 link-down trap,它不包含任何 varbinds 或指定 agentAddr 参数。

session.trap (snmp.TrapType.LinkDown, function (error) {if (error)
        console.error (error);
}); 

The following example sends an enterprise specific trap to a remote host using a SNMP version 2c trap, and includes two enterprise specific varbinds:

var trapOid = "1.3.6.1.4.1.2000.1";

var varbinds = [
    {
        oid: "1.3.6.1.4.1.2000.2",
        type: snmp.ObjectType.OctetString,
        value: "Hardware health status changed"
    },
    {
        oid: "1.3.6.1.4.1.2000.3",
        type: snmp.ObjectType.OctetString,
        value: "status-error"
    }
];

// version 2c should have been specified when creating the session
session.trap (trapOid, varbinds, function (error) {if (error)
        console.error (error);
}); 

[](https://www.npmjs.com/package… (oid, [maxRepetitions], feedCallback, doneCallback)

walk()办法获取 MIB 树中指定的 OID 之后所有 OID 的词法值。

对于 SNMP 版本 1,会反复调用 get() 办法,直到达到 MIB 树的末端。对于 SNMP 版本 2c,会反复调用getBulk(),直到达到 MIB 树的末端。

oid参数是一个 OID 字符串。当应用 SNMP 版本 2c 时,可选的 maxRepetitions 参数被传递给 getBulk() 申请。

一旦获取了所有的 OID 值,这个办法将不会调用一个回调。相同,feedCallback函数将在每次从近程主机收到响应时被调用。以下参数将被传递给 feedCallback 函数。

  • varbinds – varbinds 数组,至多蕴含一个 varbind。

当应用 SNMP 版本 2c 时,必须应用 snmp.isVarbindError() 函数查看每个 varbind 是否存在谬误条件。

一旦达到 MIB 树的起点,或者产生了谬误,doneCallback函数将被调用。以下参数将被传递给 doneCallback 函数。

  • errorError类或子类的实例,如果没有产生谬误,则为null

一旦 doneCallback 函数被调用,申请就实现了,feedCallback函数将不再被调用。

如果 feedCallback 函数在调用时返回一个 true 值,则不再调用 get()getBulk()办法,而调用doneCallback

上面的例子从 ifTable(1.3.6.1.2.1.2.2)OID 开始走到 MIB 树的最初。

var oid = "1.3.6.1.2.1.2.2";

function doneCb (error) {if (error)
        console.error (error.toString ());
}

function feedCb (varbinds) {for (var i = 0; i < varbinds.length; i++) {if (snmp.isVarbindError (varbinds[i]))
            console.error (snmp.varbindError (varbinds[i]));
        else
            console.log (varbinds[i].oid + "|" + varbinds[i].value);
    }
}

var maxRepetitions = 20;

// The maxRepetitions argument is optional, and will be ignored unless using
// SNMP verison 2c
session.walk (oid, maxRepetitions, feedCb, doneCb); 

[](https://www.npmjs.com/package… This Module: Notification Receiver

RFC 3413 classifies a “Notification Receiver” SNMP application that receives “Notification-Class” PDUs. Notifications include both SNMP traps and informs. This library is able to receive all types of notification PDU:

  • Trap-PDU (original v1 trap PDUs, which are now considered obselete)
  • Trapv2-PDU (unacknowledged notifications)
  • InformRequest-PDU (same format as Trapv2-PDU but with message acknowledgement)

The library provides a Receiver class for receiving SNMP notifications. This module exports the createReceiver() function, which creates a new Receiver instance.

The receiver creates an Authorizer instance to control incoming access. More detail on this is found below in the Authorizer Module section below.

snmp.createReceiver (options, callback)

createReceiver()函数实例化并返回一个 Receiver 类的实例。

// Default options
var options = {
    port: 162,
    disableAuthorization: false,
    accessControlModelType: snmp.AccessControlModelType.None,
    engineID: "8000B98380XXXXXXXXXXXX", // where the X's are random hex digits
    address: null
    transport: "udp4"
};

var callback = function (error, notification) {if ( error) {console.error (error);
    } else {console.log (JSON.stringify(notification, null, 2));
    }
};

receiver = snmp.createReceiver (options, callback); 

选项 ' 和 回调 ’ 参数是强制性的。options参数是一个对象,能够是空的,能够蕴含以下字段:* port – 侦听告诉的端口 – 默认为 162。

  • port– 监听告诉的端口 – 默认为 162。请留神,在某些零碎中,绑定到 162 端口须要接收器过程以管理权限运行。如果不可能,则抉择一个大于 1024 的端口。
  • `disableAuthorization’– 对所有收到的基于社区的告诉以及对收到的基于用户的告诉,如果没有音讯认证或隐衷(noAuthNoPriv),则禁用本地受权 – 默认为 false。
  • engineID — — 用于 SNMPv3 通信的引擎 ID,以十六进制字符串模式给出 — — 默认为系统生成的引擎 ID,蕴含随机元素。
  • transport — — 要应用的传输系列 — — 默认为udp4
  • address — — 要绑定的 IP 地址 — — 默认为null,即绑定到所有 IP 地址。

callback参数是一个回调函数,其模式为 function (error, notification)。在产生谬误时,”notification “ 参数被设置为 “null”。当胜利接管到一个告诉时,谬误参数被设置为nullnotification 参数被设置为一个对象,在 pdu 字段中蕴含告诉 PDU 细节,在 rinfo 字段中蕴含发送方 socket 细节。例如:

{
    "pdu": {
        "type": 166,
        "id": 45385686,
        "varbinds": [
            {
                "oid": "1.3.6.1.2.1.1.3.0",
                "type": 67,
                "value": 5
            },
            {
                "oid": "1.3.6.1.6.3.1.1.4.1.0",
                "type": 6,
                "value": "1.3.6.1.6.3.1.1.5.2"
            }
        ],
        "scoped": false
    },
    "rinfo": {
        "address": "127.0.0.1",
        "family": "IPv4",
        "port": 43162,
        "size": 72
    }
} 

[](https://www.npmjs.com/package… ()

返回接收器的 Authorizer 实例,用于管制对接收器的拜访。更多细节请参见 “Authorizer “ 局部。

[](https://www.npmjs.com/package… ()

敞开接收机的监听插座,完结接收机的操作。

Using This Module: SNMP Agent

SNMP 代理响应与命令响应器利用相干的所有四个 “ 申请类 “PDU。

  • GetRequest – 申请齐全匹配的 OID 实例。
  • GetNextRequest – 在 MIB 树中申请词法上的 “ 下一个 “OID 实例。
  • GetBulkRequest – 申请 MIB 树中的一系列 “ 下一个 “OID 实例。
  • SetRequest – 为指定的 OID 设置数值。

代理发送GetResponse PDU 到所有四种申请 PDU 类型,合乎 RFC 3416。

代理商 – 和告诉接管方一样 – 保护一个 Authorizer 实例来管制对代理的拜访,具体内容见上面的 Authorizer 模块局部。

代理保护的地方数据结构是一个 Mib 实例,其 API 详见上面的 Mib 模块局部。代理商容许通过 API 对 MIB 进行查问和操作,也容许通过 SNMP 接口与上述四个申请类 PDU 进行查问和操作。

该代理还通过其单人 Forwarder 实例反对 SNMP 代理转发利用,这在上面的 Forwarder 模块局部有阐明。

snmp.createAgent (options, callback, mib)

createAgent()函数实例化并返回一个 Agent 类的实例。

// Default options
var options = {
    port: 161,
    disableAuthorization: false,
    accessControlModelType: snmp.AccessControlModelType.None,
    engineID: "8000B98380XXXXXXXXXXXX", // where the X's are random hex digits
    address: null
    transport: "udp4"
};

var callback = function (error, data) {if ( error) {console.error (error);
    } else {console.log (JSON.stringify(data, null, 2));
    }
};

agent = snmp.createAgent (options, callback); 

选项 ' 和 回调 ’ 参数是强制性的。options参数是一个对象,能够是空的,能够蕴含以下字段。

  • port– 代理要监听的端口 – 默认为 161。请留神,在某些零碎上绑定到 161 端口须要接管方过程以管理权限运行。如果无奈做到这一点,则抉择一个大于 1024 的端口。
  • `disableAuthorization’– 对于收到的所有基于社区的告诉和基于用户的告诉,如果没有音讯认证或隐衷(noAuthNoPriv),则禁用本地受权 – 默认为 false。
  • accessControlModelType — — 指定应用哪种访问控制模型。默认值为 snmp.AccessControlModelType.None,但能够设置为snmp.AccessControlModelType.Simple,以取得更多的访问控制能力。更多信息请参见Authorization 类形容。
  • engineID– 用于 SNMPv3 通信的引擎 ID,给定为十六进制字符串 – 默认为系统生成的引擎 ID,蕴含随机元素。
  • transport — — 要应用的传输系列 — — 默认为udp4
  • address — — 要绑定的 IP 地址 — — 默认为null,即绑定到所有 IP 地址。

mib参数是可选的,它设置了代理的单体 Mib 实例。如果不提供,代理会给本人创立一个新的空的 Mib 单体。如果提供,则须要依照上面的 Mib 模块局部来创立和填充 Mib 实例。

agent.getAuthorizer ()

返回代理的单人 Authorizer 实例,用于管制对代理的拜访。更多细节请参见 “Authorizer “ 局部。

agent.getMib ()

Returns the agent’s singleton Mib instance, which holds all the management data for the agent.

agent.setMib (mib)

Sets the agent’s singleton Mib instance to the supplied one. The agent discards its existing Mib instance.

[](https://www.npmjs.com/package… ()

Returns the agent’s singleton Forwarder instance, which holds a list of registered proxies that specify context-based forwarding to remote hosts.

[](https://www.npmjs.com/package… ()

Closes the agent’s listening socket, ending the operation of the agent.

[](https://www.npmjs.com/package… Module

接收器和代理都保护一个单例的 “Authorizer “ 实例,它负责保护 SNMP 社区的受权列表(针对 v1 和 v2c 告诉)和 SNMP 用户的受权列表(针对 v3 告诉)。这些列表用于受权接管方对告诉的拜访,并存储平安协定和密钥设置。RFC 3414 将用户列表称为存储在接收器的 “ 本地配置数据库 “ 中的 “usmUserTable”。

如果收到的 v1 或 v2c 告诉中的社区不在接收器的社区受权列表中,接收器将不承受该告诉,而是向提供的回调函数返回一个类 RequestFailedError 的谬误。相似的,如果接管到一个 v3 告诉,其用户名称不在接收者的用户受权列表中,接收者将返回一个 RequestFailedError。如果在启动时为接收器提供了disableAuthorization 选项,那么对于社区告诉和 noAuthNoPriv 用户告诉,这些本地受权列表查看将被禁用。请留神,即便有这个设置,用户列表依然会对 authNoPriv 和 authPriv 告诉进行查看,因为库依然须要拜访正确的密钥来进行音讯认证和加密操作,而这些密钥是针对用户受权列表中的用户存储的。

API 容许对接收者 / 代理的社区受权和用户受权列表进行增加、查问和删除治理。

对于代理来说,还有一个可选的访问控制查看,它能够依据代理提供的作为选项的 AccessControlModelType 来限度给定社区或用户的拜访。默认的模型类型是 snmp.AccessControlModelType.None,这意味着 – 在后面几段形容的受权列表查看之后,没有进一步的访问控制限度,即所有申请都被代理授予拜访权。能够抉择第二个访问控制模型类型snmp.AccessControlModelType.Simple,它创立了一个SimpleAccessControlModel 对象,该对象能够被操作,以指定社区或用户对代理信息具备三个级别的拜访权限之一。

  • 只读

* 读写器

对于如何应用 “SimpleAccessControlModel “ 类配置拜访的更多信息,将在上面对该类的形容中提供。

受权器实例能够通过应用 getAuthorizer() 调用取得,对于接管方和代理方来说都是如此。例如:

receiver.getAuthorizer ().getCommunities (); 

authorizer.addCommunity (community)

在接收者的社区受权列表中增加一个社区字符串。如果社区曾经在列表中,则不做任何操作,确保列表中任何给定的社区字符串只呈现一次。

[](https://www.npmjs.com/package… (community)

如果接收者的社区受权列表中存储了一个社区字符串,则返回 “null”,否则返回 “null”。

authorizer.getCommunities ()

返回接收者的社区受权列表。

authorizer.deleteCommunity (community)

从接收者的社区受权列表中删除一个社区字符串。如果社区不在列表中,则不做任何操作。

authorizer.addUser (user)

在接管方的用户受权列表中增加一个用户。如果列表中存在同名用户,则该调用将删除现有用户,并以提供的用户取而代之,确保列表中只存在一个同名用户。用户对象的格局与 session.createV3Session() 调用的格局雷同。

var user = {
    name: "elsa"
    level: snmp.SecurityLevel.authPriv,
    authProtocol: snmp.AuthProtocols.sha,
    authKey: "imlettingitgo",
    privProtocol: snmp.PrivProtocols.des,
    privKey: "intotheunknown"
};

receiver.getAuthorizer ().addUser (elsa); 

authorizer.getUser (userName)

如果接收者的用户受权列表中存储了一个应用所提供名字的用户,则返回一个用户对象,否则返回null

authorizer.getUsers ()

Returns the receiver’s user authorization list.

authorizer.deleteUser (userName)

Deletes a user from the receiver’s user authorization list. Does nothing if the user with the supplied name is not in the list.

authorizer.getAccessControlModelType ()

Returns the snmp.AccessControlModelType of this authorizer, which is one of:

  • snmp.AccessControlModelType.None
  • snmp.AccessControlModelType.Simple

authorizer.getAccessControlModel ()

Returns the access control model object:

  • for a type of snmp.AccessControlModelType.None – returns null (as the access control check returns positive every time)
  • for a type of snmp.AccessControlModelType.Simple – returns a SimpleAccessControlModel object

[](https://www.npmjs.com/package… Access Control Model

SimpleAccessControlModel' 类能够抉择作为 Agent’ 应用的访问控制模型。SimpleAccessControlModel 为给定的社区或用户提供根本的三级访问控制。拜访级别由 snmp.AccessLevel 常量指定。

  • snmp.AccessLevel.None– 不授予社区或用户任何拜访权。
  • `snmp.AccessLevel.ReadOnly’ — — 容许社区或用户拜访 Get、GetNext 和 GetBulk 申请,但不容许拜访 Set 申请。
  • snmp.AccessLevel.ReadWrite — — 容许社区或用户拜访 Get、GetNext、GetBulk 和 Set 申请。

SimpleAccessControlModel不是通过间接的 API 调用创立的,而是由 AgentAuthorizer单人在外部创立的。所以能够用以下办法拜访代理的访问控制模型。

var acm = agent.getAuthorizer ().getAccessControlModel (); 

请留神,本节中任何 API 调用中应用的任何社区或用户都必须首先在代理的 “ 受权者 “ 中创立,否则代理将无奈通过受权者执行的初始社区 / 用户列表查看。

当应用简略访问控制模型时,Authorizer中新创建的社区或用户的默认拜访级别是只读。

Example use:

var agent = snmp.createAgent({accessControlModelType: snmp.AccessControlModelType.Simple}, function (error, data) {// null callback for example brevity});
var authorizer = agent.getAuthorizer ();
authorizer.addCommunity ("public");
authorizer.addCommunity ("private");
authorizer.addUser ({
    name: "fred",
    level: snmp.SecurityLevel.noAuthNoPriv
});
var acm = authorizer.getAccessControlModel ();
// Since read-only is the default, explicitly setting read-only access is not required - just shown here as an example
acm.setCommunityAccess ("public", snmp.AccessLevel.ReadOnly);
acm.setCommunityAccess ("private", snmp.AccessLevel.ReadWrite);
acm.setUserAccess ("fred", snmp.AccessLevel.ReadWrite); 

simpleAccessControlModel.setCommunityAccess (community, accessLevel)

Grant the given community the given access level.

[](https://www.npmjs.com/package… (community)

Remove all access for the given community.

[](https://www.npmjs.com/package… (community)

Return the access level for the given community.

[](https://www.npmjs.com/package… ()

Return a list of all community access control entries defined by this access control model.

[](https://www.npmjs.com/package… (userName, accessLevel)

Grant the given user the given access level.

[](https://www.npmjs.com/package… (userName)

Remove all access for the given user.

[](https://www.npmjs.com/package… (userName)

Return the access level for the given user.

[](https://www.npmjs.com/package… ()

Return a list of all user access control entries defined by this access control model.

Mib Module

代理 ' 实例在创立时,又创立了 Mib’ 类的一个实例。一个代理总是有且只有一个Mib 实例。通过 agent.getMib() 调用来拜访代理的 Mib 实例。

MIB 是一个树状构造,它保留着治理信息。信息在树中由一系列整数 “ 寻址 ”,这些整数从树的根部向下造成一个对象 ID(OID)。

在 MIB 中,只有两种数据结构能够保留数据。

标量 数据 – 标量变量存储在 MIB 树的某个节点上,变量的值是标量变量节点的单个子节点,地址总是 “0”。例如,sysDescr 标量变量的地址为 “1.3.6.1.2.1.1.1”。sysDescr 变量的值存储在 “1.3.6.1.2.1.1.0”


```
1.3.6.1.2.1.1.1 <= sysDescr (标量变量)
1.3.6.1.2.1.1.0 = OctetString: MyAwesomeHost <= sysDescr.0 (标量变量值) 
```

* 表 数据 –SNMP 表以列和行的模式存储数据。通常状况下,如果一个表存储在 MIB 中的某个节点上,那么在表 OID 的正下方有一个地址为 “1 “ 的 “ 条目 “ 对象。在 “ 条目 “ 的正下方是一个列的列表,这些列的编号通常是从 “1 “ 往上的。在每一列的上面是一系列的行。在最简略的状况下,一行的 “ 索引 “ 是表中的一列,但行索引能够是一系列列,也能够是给出多个整数的列(如一个 IPv4 地址的索引有四个整数),或者两者都有。上面是 ifTable 中局部 SNMP 表的层次结构的例子。


```
1.3.6.1.2.1.2.2 <= ifTable (table)
1.3.6.1.2.1.2.2.1 <= ifEntry (表项)
1.3.6.1.2.1.2.2.1.1 <= ifIndex (第 1 栏)
1.3.6.1.2.1.2.1.1 = Integer: 1 <= ifIndex row 1 value = 1。1.3.6.1.2.1.2.2.1.1.2 = Integer: 2 <= ifIndex row 2 value = 2。```

在创立时,”Agent “ 实例会创立一个 “Mib “ 模块的单人实例。而后,您能够向代理的 Mib 实例注册一个 “ 提供者 ”,它为标量数据实例或表提供一个接口。

var myScalarProvider = {
    name: "sysDescr",
    type: snmp.MibProviderType.Scalar,
    oid: "1.3.6.1.2.1.1.1",
    scalarType: snmp.ObjectType.OctetString,
    handler: function (mibRequest) {
       // e.g. can update the MIB data before responding to the request here
       mibRequest.done ();}
};
var mib = agent.getMib ();
mib.registerProvider (myScalarProvider);
mib.setScalarValue ("sysDescr", "MyAwesomeHost"); 

这段代码首先给出了标量 “ 提供者 “ 的定义。在 mib.registerProvider() 局部对这些字段做了进一步的解释。重要的是,name字段是提供者的惟一标识符,在后续的 API 调用中用于抉择特定的提供者。

registerProvider()调用将提供者增加到 MIB 持有的提供者列表中。请留神,这个调用不会将 “oid “ 节点增加到 MIB 树中。第一次调用 setScalarValue() 将把实例 OID “1.3.6.1.2.1.1.1.0 “ 连同其值一起增加到 MIB 树中。

此时,当通过 SNMP 查问实例 OID “1.3.6.1.1.2.1.1.1.0 “ 时,代理将提供该 MIB 节点的值。

一个表提供者也有相似的定义。

var myTableProvider = {
    name: "smallIfTable",
    type: snmp.MibProviderType.Table,
    oid: "1.3.6.1.2.1.2.2.1",
    tableColumns: [
        {
            number: 1,
            name: "ifIndex",
            type: snmp.ObjectType.Integer
        },
        {
            number: 2,
            name: "ifDescr",
            type: snmp.ObjectType.OctetString
        },
        {
            number: 3,
            name: "ifType",
            type: snmp.ObjectType.Integer,
            constraints: {
                enumeration: {
                    "1": "goodif",
                    "2": "averageif",
                    "3": "badif"
                }
            }
        }
    ],
    tableIndex: [
        {columnName: "ifIndex"}
    ]
};
var mib = agent.getMib ();
mib.registerProvider (myTableProvider);
mib.addTableRow ("smallIfTable", [1, "eth0", 6]); 

在这里,提供者的定义须要两个增加字段。tableColumns示意列的定义,tableIndex示意用于行索引的列。在本例中,tableIndexifIndex 列。mib.registerProvider()局部有对于形成提供者定义的字段的进一步细节。

oid必须是 “ 表条目 “ 节点的节点,而不是它的父 “ 表 “ 节点,例如对于 ifTable,提供者中的oid 是 “1.3.6.1.2.1.2.2.1”(ifEntry的 OID)。

请留神,在这个非凡的例子中,没有 handler 回调函数,所以任何交互都是间接在 SNMP 申请和 MIB 值之间进行,没有其余干涉。

snmp.createMib ()

createMib()函数实例化并返回一个 Mib 类的实例。新的 Mib 没有任何节点(除了一个根节点),也没有任何注册的提供者。

请留神,这只实用于一个代理,而不是 AgentX 子代理。因为代理在创立时就会实例化一个 Mib 实例,所以在很多状况下不须要这个调用。有两种状况可能会用到它。

  • 在创立 Agent 实例之前,你想用提供者和标量 / 表格数据事后填充一个 Mib 实例。
  • 你想把一个代理的现有 Mib 实例换成一个全新的实例。

mib.registerProvider (definition)

在 MIB 中注册一个提供者定义。不向 MIB 树增加任何内容。

提供者定义有以下几个字段:* name (强制性的) – 提供者的名称。

  • name (强制) – 提供方的名称,它是获取和设置值时援用提供方的惟一键。
  • type (强制性) – 必须是 snmp.MibProviderType.Scalarsnmp.MibProviderType.Table(强制性)
  • oid(必须填写) - 提供者在 MIB 树中注册的 OID。请留神,这不是 * 的 “ 实例节点 ”(”.0 “ 节点),而是它下面的节点。在这种状况下,提供者在 “1.3.6.1.2.1.1.1 “ 处注册,以提供 “1.3.6.1.2.1.1.0 “ 处的值。
  • scalarType (标量类型必须填写) - 只与标量提供者类型相干,这给出了变量的类型,从 snmp.ObjectType 中抉择。
  • tableColumns (表类型必须填写) — — 提供表的任何列定义对象数组。每个列对象必须有一个独特的 数字 '、名称 ’ 和 snmp.ObjectType' 的 类型 ’。类型为 ObjectType.Integer 的列对象能够选择性地蕴含一个 constraints 对象,其格局和含意与在单个标量提供者上定义的对象雷同(具体内容见下文constraints)。
  • tableIndex (表类型可选) - 给出一个用于行索引的索引入口对象数组。对于单列索引应用单元素数组,对于复合索引应用多个值。一个索引条目对象有一个 columnName 字段,如果条目在另一个提供者的表中,那么包含一个 foreign 字段,写上表面提供者的名称。如果没有 tableAugments 字段,tableIndex是必须的。
  • tableAugments (表类型可选) - 给出本表 “ 加强 “ 的另一个注册提供者的名称。这意味着索引信息是从给定提供者的表中获取的,并且不存在于本地表的列定义中。如果 tableIndex 字段不存在,tableAugments是必须的,即 tableIndextableAugments中的一个须要存在,能力定义表的索引。
  • handler (optional) – 一个可选的回调函数,在向 MIB 提出申请之前被调用。这能够更新这个提供者解决的 MIB 值。如果没有给定,那么这些值将被简略地从 MIB 中返回(或设置),而不须要任何其余解决。回调函数须要一个 MibRequest 实例,它有一个 done() 函数。当解决完申请时,必须调用这个函数。MibRequest也有一个 oid 字段,写着被操作的实例 OID,还有一个 operation 字段,写着来自 snmp.PduType 的申请类型。如果 “MibRequest “ 是针对 “SetRequest “PDU 的,那么变量 “setValue “ 和 “setType “ 就蕴含了 “SetRequest “varbind 中接管到的值和类型。
  • constraints (对于标量类型是可选的) – 一个可选的对象,用于指定基于整数的枚举类型的束缚。目前惟一反对的束缚是 enumeration 对象,它将整数映射到它们的命名类型,以捕捉 RFC 2578 第 7.1.1 节中形容的 “ 命名数枚举 ”。任何 SetRequest 协定操作都会依据定义的约束条件进行查看,如果 SetRequest 中的值会违反约束条件,例如该值不是定义的枚举的成员,则不会采取行动。请留神,表列能够以雷同的形式指定这样的 “ 束缚 ”,只是这些束缚存储在每个列的列对象定义下。

在向 MIB 注册提供者后,在其余 API 调用中,提供者由其 名称 援用。

尽管这个调用将提供者注册到 MIB,但它不会扭转 MIB 树。

mib.registerProviders ([definitions] )

Convenience method to register an array of providers in one call. Simply calls registerProvider() for each provider definition in the array.

mib.unregisterProvider (name)

Unregisters a provider from the MIB. This also deletes all MIB nodes from the provider’s oid down the tree. It will also do upstream MIB tree pruning of any interior MIB nodes that only existed for the MIB tree to reach the provider oid node.

mib.getProviders ()

Returns an object of provider definitions registered with the MIB, indexed by provider name.

mib.getProvider (name)

Returns a single registered provider object for the given name.

mib.getScalarValue (scalarProviderName)

Retrieves the value from a scalar provider.

mib.setScalarValue (scalarProviderName, value)

Sets the value for a scalar provider. If this is the first time the scalar is set since the provider has registered with the MIB, it will also add the instance (“.0”) node and all required ancestors to the MIB tree.

mib.addTableRow (tableProviderName, row)

将表行 – 以值数组的模式 – 增加到表提供者。如果表是空的,则在增加值行之前,实例化提供者的 oid 节点和先人,即其列。请留神,该行是一个依照表列顺序排列的元素数组。如果表有任何外来索引列(即那些不属于本表的索引列),那么这些列的值必须依照它们在 MIB INDEX 子句中呈现的程序,蕴含在行数组的结尾。

mib.getTableColumnDefinitions (tableProviderName)

Returns a list of column definition objects for the provider.

mib.getTableCells (tableProviderName, byRow, includeInstances)

返回表格数据的二维数组。如果 byRow 为 false(默认),那么表格数据是以列数组列表的模式给出的,即按列给出。如果 byRowtrue,那么数据就是一个行数组的列表。如果 includeInstancestrue,那么,对于列视图,将有一个额定的第一列的实例索引信息。如果行视图中 includeInstancestrue,那么在每一行的开始会有一个附加元素,蕴含索引信息。

mib.getTableColumnCells (tableProviderName, columnNumber, includeInstances)

Returns a single column of table data for the given column number. If includeInstances is true, then two arrays are returned: the first with instance index information, and the second with the column data.

mib.getTableRowCells (tableProviderName, rowIndex)

返回给定行索引的单行表数据。行索引是一个由索引值组成的数组,从紧挨着列下的节点到行实例开端的节点,这将是 MIB 树中的一个叶子节点。最终,非整数值须要转换为整数序列,形成 OID 的实例局部。上面是将索引值转换为行实例 OID 序列的细节。

  • ObjectType.Integer – 单个整数。
  • ObjectType.OctetString – 一个 ASCII 值的整数序列。
  • ObjectType.OID – OID 中的确切整数序列。
  • ObjectType.IpAddress – IP 地址中四个整数的序列。

mib.getTableSingleCell (tableProviderName, columnIndex, rowIndex)

Returns a single cell value from the column and row specified. The row index array is specified in the same way as for the getTableRowCells() call.

mib.setTableSingleCell (tableProviderName, columnIndex, rowIndex, value)

Sets a single cell value at the column and row specified. The row index array is specified in the same way as for the getTableRowCells() call.

mib.deleteTableRow (tableProviderName, rowIndex)

Deletes a table row at the row index specified. The row index array is specified in the same way as for the getTableRowCells() call. If this was the last row in the table, the table is pruned from the MIB, although the provider still remains registered with the MIB. Meaning that on the addition of another row, the table will be instantiated again.

[](https://www.npmjs.com/package… (options)

以文本格式转储 MIB。options对象通过这些选项字段管制转储的显示(所有选项都是布尔值,默认为true)。

  • leavesOnly– 不独自显示外部节点 – 只显示叶子节点的前缀局部(实例节点)。
  • showProviders — — 显示提供者与 MIB 相连的节点。
  • “showTypes” — — 显示实例价值类型。
  • showValues – 显示实例值。

For example:

mib.dump (); 

produces this sort of output:

1.3.6.1.2.1.1.1 [Scalar: sysDescr]
1.3.6.1.2.1.1.1.0 = OctetString: Rage inside the machine!
1.3.6.1.2.1.2.2.1 [Table: ifTable]
1.3.6.1.2.1.2.2.1.1.1 = Integer: 1
1.3.6.1.2.1.2.2.1.1.2 = Integer: 2
1.3.6.1.2.1.2.2.1.2.1 = OctetString: lo
1.3.6.1.2.1.2.2.1.2.2 = OctetString: eth0
1.3.6.1.2.1.2.2.1.3.1 = Integer: 24
1.3.6.1.2.1.2.2.1.3.2 = Integer: 6 

Using This Module: Module Store

该库反对 MIB 解析,为 ModuleStore 实例提供了一个接口,您能够从文件中加载 MIB 模块,并获取由此产生的 JSON MIB 模块示意。

此外,一旦一个 MIB 被加载到模块存储中,你就能够生成一个 MIB “ 提供者 “ 定义的列表,一个 “ 代理 “ 能够注册(更多细节请参见 “ 代理 “ 文档),这样你就能够马上开始操作你的 MIB 文件中定义的所有值。

// Create a module store, load a MIB module, and fetch its JSON representation
var store = snmp.createModuleStore ();
store.loadFromFile ("/path/to/your/mibs/SNMPv2-MIB.mib");
var jsonModule = store.getModule ("SNMPv2-MIB");

// Fetch MIB providers, create an agent, and register the providers with your agent
var providers = store.getProvidersForModule ("SNMPv2-MIB");
// Not recommended - but authorization and callback turned off for example brevity
var agent = snmp.createAgent ({disableAuthorization: true}, function (error, data) {});
var mib = agent.getMib ();
mib.registerProviders (providers);

// Start manipulating the MIB through the registered providers using the `Mib` API calls
mib.setScalarValue ("sysDescr", "The most powerful system you can think of");
mib.setScalarValue ("sysName", "multiplied-by-six");
mib.addTableRow ("sysOREntry", [1, "1.3.6.1.4.1.47491.42.43.44.45", "I've dreamed up this MIB", 20]);

// Then hit those bad boys with your favourite SNMP tools (or library ;-), e.g.
snmpwalk -v 2c -c public localhost 1.3.6.1 

这意味着您能够用起码的模板代码间接实现您的 MIB 性能。

snmp.createModuleStore ()

创立一个新的 ModuleStore 实例,该实例预装了一些 “ 根底 “MIB 模块,这些模块提供了其余 MIB 模块罕用的 MIB 定义(” 导入 ”)。预装的 “ 根底 “ 模块列表如下:

  • RFC1155-SMI
  • RFC1158-MIB
  • RFC-1212
  • RFC1213-MIB
  • SNMPv2-SMI
  • SNMPv2-CONF
  • SNMPv2-TC
  • SNMPv2-MIB

store.loadFromFile (fileName)

将给定文件中的所有 MIB 模块加载到模块存储中。依照常规,每个文件中通常只有一个 MIB 模块,但一个文件中能够存储多个模块定义。而后,加载的 MIB 模块被这个 API 用它们的 MIB 模块名而不是源文件名来援用。MIB 模块名是 MIB 文件中 DEFINITIONS ::= BEGIN 后面的名称,通常是 MIB 文件中最先呈现的货色。

请留神,如果您的 MIB 依赖于(” 导入 ”)其余 MIB 文件中的定义,则必须首先加载这些定义,例如,风行的 IF-MIB 应用了来自 IANAifType-MIB 的定义,因而必须首先加载。这些依赖关系列在 MIB 模块的 IMPORTS 局部,通常在 MIB 文件的顶部。事后加载的 “ 根底 “MIB 模块蕴含了许多罕用的导入。

store.getModule (moduleName)

Retrieves the named MIB module from the store as a JSON object.

store.getModules (includeBase)

从商店中检索所有的 MIB 模块,如果includeBaseboolean 被设置为 true,那么根本的 MIB 模块就会被蕴含在列表中。如果 “includeBase “ 布尔值被设置为 true,那么根本的 MIB 模块就被蕴含在列表中。模块作为一个繁多的 JSON “ 对象中的对象 “ 返回,以模块名称为键,其值是整个 JSON 模块的示意。

store.getModuleNames (includeBase)

Retrieves a list of the names of all MIB modules loaded in the store. If the includeBase boolean is set to true, then the base MIB modules names are included in the list.

store.getProvidersForModule (moduleName)

Returns an array of Mib “provider” definitions corresponding to all scalar and table instance objects contained in the named MIB module. The list of provider definitions are then ready to be registered to an agent’s MIB by using the agent.getMib().registerProviders() call.

Forwarder Module

代理 ' 实例在创立后,又会创立 Forwarder’ 类的实例。没有间接的 API 调用来创立 “Forwarder “ 实例;这种创立是代理的责任。一个代理总是只有一个Forwarder 实例。代理的 Forwarder 实例是通过 agent.getForwarder() 调用来拜访的。

Forwader就是 RFC 3413 所说的 “ 代理转发利用 ”。它保护着一个 “ 代理 “ 条目列表,每个条目都配置了一个命名的 SNMPv3 上下文名称,以使用户凭证可能拜访给定的指标主机。Forwarder只反对 SNMPv3 会话的代理。

var forwarder = agent.getForwarder ();
forwarder.addProxy({
    context: "slatescontext",
    host: "bedrock",
    user: {
        name: "slate",
        level: snmp.SecurityLevel.authNoPriv,
        authProtocol: snmp.AuthProtocols.sha,
        authKey: "quarryandgravel"
    },
}); 

当初,应用所提供的 “slatescontext “ 上下文向代理收回的申请将被转发到主机 “bedrock”,并应用所提供的用户 “slate “ 的证书。

你能够应用本地代理用户(与代理的 Authorizer 实例一起增加)查问代理。假如你的代理运行在 localhost,161 端口,你能够增加本地用户 “fred”,而后用新的 “fred “ 用户拜访代理。

var authorizer = agent.getAuthorizer();
authorizer.addUser ({
    name: "fred",
    level: snmp.SecurityLevel.noAuthNoPriv
});

// Test access using Net-SNMP tools (-n is the context option):

snmpget -v 3 -u fred -l noAuthNoPriv -n slatescontext localhost 1.3.6.1.2.1.1.1.0 

This proxies requests through to “bedrock” as per the proxy definition.

forwarder.addProxy (proxy)

为转发者增加一个新的代理。代理是一个蕴含以下字段的对象。

  • context (强制) – 这个代理条目标 SNMPv3 上下文名称。这是代理条目标惟一键,即不能有两个代理条目标上下文名称雷同。
  • transport (可选) – 指定达到远程目标的传输。能够是 udp4udp6,默认为udp4
  • target (强制) – 接管代理申请的近程主机。
  • port (可选) – 近程主机上 SNMP 代理的端口。默认值为 161。
  • user (必填) – SNMPv3 用户。用户的格局在 createV3Session() 调用文档中形容。

forwarder.deleteProxy (context)

Delete the proxy for the given context from the forwarder.

forwarder.getProxy (context)

Returns the forwarder’s proxy for the given context.

forwarder.getProxies ()

Returns an object containing a list of all registered proxies, keyed by context name.

[](https://www.npmjs.com/package… ()

Prints a dump of all proxy definitions to the console.

Using This Module: AgentX Subagent

AgentX 子代理实现了 RFC 2741 中指定的性能,成为 AgentX “ 主代理 “ 的一个 “ 子代理 ”。AgentX 的指标是通过一个独自的 “ 子代理 “ 来扩大现有的 “ 主代理 “SNMP 代理的性能,注册它想为主代理治理的 MIB 树的局部。

除了两个 “ 治理 “PDU 类型外,AgentX 子代理反对生成所有的 PDU 类型,所有的 PDU 都是从子代理发送到主代理的。

  • Open PDU– 关上与主代理的新会话
  • 敞开 PDU – 敞开与主代理的现有会话。
  • 注册 PDU — — 注册一个 MIB 区域,以便与主代理进行管制。
  • 解除注册 PDU — — 解除以前向主代理注册的 MIB 区域的注册。
  • Notify PDU – 向主代理发送告诉。
  • Ping PDU – 发送 “Ping “ 以确认主代理依然可用。
  • AddAgentCaps PDU – 在主代理的 sysORTable 中增加代理性能。
  • RemoveAgentCaps PDU– 从主代理的 sysORTable 中删除以前增加的代理性能。

两种不反对的 “ 治理 “PDU 类型是:* IndexAllocate PDU – 申请从索引由主代理治理的表调配索引。

  • IndexAllocate PDU– 申请调配由主代理治理索引的表的索引。
  • IndexDeallocate PDU — — 申请从主代理的表中重新分配以前调配的索引。

这些都是不反对的,因为它们不适宜以后的 MIB 提供者注册模型,该模型只反对注册标量和整个表格。未来能够通过进一步概括注册模型来反对表行注册来反对这些。

子代理响应所有与命令响应者利用相干的 “ 申请解决 “PDU 类型,这些类型是从主代理接管的。

  • Get PDU– 申请齐全匹配的 OID 实例。
  • GetNext PDU– 申请 MIB 树中的词法 “ 下一个 “OID 实例。
  • GetBulk PDU — — 申请 MIB 树中一系列的 “ 下一个 “OID 实例。
  • TestSet PDU – 测试将作为繁多事务提交的 “ 集 “ 操作列表。
  • CommitSet PDU – 将一系列 “set “ 操作作为繁多事务提交。
  • UndoSet PDU — — 将 “set “ 操作列表作为繁多事务撤销。
  • CleanupSet PDU — — 完结 “ 设置 “ 事务。

依据 RFC 2741,除了 CleanupSet PDU 外,所有这些都会返回一个 Response PDU 给主代理。

与 SNMP 代理一样,AgentX 子代理保护的是一个 Mib 实例,其 API 在下面的 Mib 模块局部有具体介绍。子代理容许通过 API 查问和操作 MIB,也容许通过 AgentX 接口查问和操作上述 “ 申请解决 “PDU(当主代理调用其 SNMP 接口时,主代理会产生)。

重要的是,MIB 提供者是应用子代理的 subagent.registerProvider() 调用来注册的 (如下所述),而不是应用subagent.getMib().registerProvider(),因为子代理既须要在其外部Mib 对象上注册提供者,_又须要为提供者的 MIB 区域发送一个 Register PDU 给主代理。如果间接在 MIB 对象上注册提供者,则跳过后一步。

snmp.createSubagent (options)

The createSubagent () function instantiates and returns an instance of the Subagent class:

// Default options
var options = {
    master: localhost
    masterPort: 705,
    timeout: 0,
    description: "Node net-snmp AgentX sub-agent",
};

subagent = snmp.createSubagent (options); 

The options parameter is a mandatory object, possibly empty, and can contain the following fields:

  • master – the host name or IP address of the master agent, which the subagent connects to.
  • masterPort – the TCP port for the subagent to connect to the master agent on – defaults to 705.
  • timeout – set the session-wide timeout on the master agent – defaults to 0, which means no session-wide timeout is set.
  • description – a textual description of the subagent.

[](https://www.npmjs.com/package… ()

Returns the agent’s singleton Mib instance, which is automatically created on creation of the subagent, and which holds all of the management data for the subagent.

[](https://www.npmjs.com/package… (callback)

Sends an Open PDU to the master agent to open a new session, invoking the callback on response from the master.

[](https://www.npmjs.com/package… (callback)

Sends a Close PDU to the master agent to close the subagent’s session to the master, invoking the callback on response from the master.

[](https://www.npmjs.com/package… (provider, callback)

See the Mib class registerProvider() call for the definition of a provider. The format and meaning of the provider object is the same for this call. This sends a Register PDU to the master to register a region of the MIB for which the master will send “request processing” PDUs to the subagent. The supplied callback is used only once, on reception of the subsequent Response PDU from the master to the Register PDU. This is not to be confused with the handler optional callback on the provider definition, which is invoked for any “request processing” PDU received by the subagent for MIB objects in the registered MIB region.

[](https://www.npmjs.com/package… (name, callback)

Unregisters a previously registered MIB region by the supplied name of the provider. Sends an Unregister PDU to the master agent to do this. The supplied callback is used only once, on reception of the subsequent Response PDU from the master to the Unregister PDU.

[](https://www.npmjs.com/package… ( [definitions], callback )

Convenience method to register an array of providers in one call. Simply calls registerProvider() for each provider definition in the array. The callback function is called once for each provider registered.

[](https://www.npmjs.com/package… ()

Returns an object of provider definitions registered with the MIB, indexed by provider name.

[](https://www.npmjs.com/package… (name)

Returns a single registered provider object for the given name.

[](https://www.npmjs.com/package… (oid, descr, callback)

Adds an agent capability – consisting of oid and descr – to the master agent’s sysORTable. Sends an AddAgentCaps PDU to the master to do this. The supplied callback is called on reception of the subsequent Response PDU from the master to the AddAgentCaps PDU.

[](https://www.npmjs.com/package… (oid, callback)

Remove an previously added capability from the master agent’s sysORTable. Sends a RemoveAgentCaps PDU to the master to do this. The supplied callback is called on reception of the subsequent Response PDU from the master to the RemoveAgentCaps PDU.

[](https://www.npmjs.com/package… (typeOrOid, varbinds, callback)

Sends a notification to the master agent using a Notify PDU. The notification takes the same form as outlined in the session.inform() section above and also in RFC 2741 Section 6.2.10, which is creating two varbinds that are always included in the notification:

  • sysUptime.0 (1.3.6.1.2.1.1.3.0) – containing the subagent’s uptime
  • snmpTrapOID.0 (1.3.6.1.6.3.1.1.4.1.0) – containing the supplied OID (or supplied snmp.TrapType value)

The optional varbinds list is an additional list of varbind objects to append to the above two varbinds. The supplied callback is called on reception of the subsequent Response PDU from the master to the Notify PDU.

[](https://www.npmjs.com/package… (callback)

Sends a “ping” to the master agent using a Ping PDU, to confirm that the master agent is still responsive. The supplied callback is called on reception of the subsequent Response PDU from the master to the Ping PDU.

[](https://www.npmjs.com/package… Programs

Example programs are included under the module’s example directory.

正文完
 0