# MIB and OID

SNMP介绍
SNMP介绍
1.1. SNMP概览
SNMP的基本知识介绍

SNMP对于任何程序设计人员来说是特别易于理解的。总体的简化能够很好地把这个系统简化。一个网络设备以守护进程的方式运行SNMP代理，该守护进程能够响应来自网络的各种请求信息。该SNMP代理提供大量的对象标识符（OID－Object Identifiers）。一个OID是一个唯一的键值对。该代理存放这些值并让它们可用。一个SNMP管理器（客户）可以向代理查询键值对中的特定信息。从程序员的角度看，这和导入大量的全局变量没有多少区别。SNMP的OID是可读或可写的。尽管向一个SNMP设备写入信息的情况非常少，但它是各种管理应用程序用来控制设备的方法（例如针对交换机的可管理GUI）。SNMP中有一个基本的认证框架，能够让管理员发送公共名来对OID读取或写入的认证。绝大多数的设备使用不安全的公共名 "public" 。 SNMP协议通过UDP端口161和162进行通信的。

SNMP可以按照两种方式来使用：轮询和陷阱。轮询就是说你编写一个应用程序能够设置一个发送给一个SNMP代理查看某些值的SNMP GET请求。这种方法非常有用，因为如果该设备响应了请求，你就得到了你需要的信息，如果该设备没有响应请求，你就能够知道存在某些问题。轮询是网络监控的一种主动形式。另一方面，SNMP陷阱能够被用来进行被动形式的网络监控。SNMP陷阱是通过配置SNMP设备的代理，让他在某些动作发生时联系另一个SNMP代理来实现的。

SNMP被广泛应用在NMS网络管理系统中（Network Management System）。知名的NMS包括BMC的Patrol、CA的Unicenter、Sun Mangegement控制台、IBM的Tivoli Netview、以及全球著名的HP Openview。NMS的目标是提供一个监控和管理所有开启SNMP功能的设备的单一入口。通过配置你的设备代理来接受写访问，你可以从一个应用程序中处理你的网络环境。如果你的整个环境围拢NMS解决方案架构你的环境，你就能无限制地控制、查看你的整个网络。尽管Net-SNMP提供了可用来构建你自己的NMS网管系统的所有工具，我们不会再进一步讨论关于NMS的话题。不过请记住，如果你认为你的SNMP设备厂商没有提供SNMP代理方面的详细信息，很可能是因为他们希望你购买他们的NMS网络管理系统，或者购买能够在另一个NMS平台上使用的插件。
1.2. SNMP的三大版本
SNMP的常用版本有三个：SNMPv1、SNMPv2、SNMPv3
Three different version of SNMP exist: SNMPv1 (RFC’s 1155, 1157, and 1212), SNMPv2c (RFC’s 1901 through 1908), and SNMPv3 (RFC’s 3411 though 3418). The co-existence of all three versions are detailed in RFC 3584.

SNMP有三个不同的版本：SNMPv1(RFC 1155、RFC 1157、RFC 1212),SNMPv2c (RFC 1901、1908）以及 SNMPv3 (RFC 3411 - 3418). RFC 3584中详细说明了这三种版本同时共存方面的信息。
SNMPv1 is the original standard for community based management. SNMPv2 was derived from the SNMPv1 framework but had no message definition, which was later revamped aa SNMPv2c, a community based version of SNMPv2 with a message format similar to SNMPv1. SNMPv2 added several new datatypes (Counter32, Counter64, Gauge32, UInteger32, NsapAdress, and BIT STRING), as well as enhancements to OID tables and the setting of OID values. SNMPv3 is an extensable SNMPv2 framework with a new message format, ACL and security abilities, and remote configuration of SNMP parameters.

SNMP is based on several other standards including the Abstract Syntax Notation 1 Basic Encoding Rules (ASN.1 BER) which defines the SNMP used Datatypes and the Structure of Management Information (SMI) which details the grammar used by SNMP MIBs. SMI comes in two varieties: SMIv1 (RFC 1155) and SMIv2 (RFC 2578). SMIv1 is now obsolete and should not be used. If you choose to modify MIBs at some point you’ll need to learn SMIv2 and ASN.1 syntax, but otherwise they are interesting but unnecessary to learn.

SNMP是基于几个其他规范的，包括定义给予SNMP的数据类型的ASN.1 BER(Abstract Syntax Notation 1 Basic Encoding Rules), 以及详细描述有SNMP MIB使用的语法的管理信息结构（SMI）。SMIv1目前被独立出来，不应当再被使用。如果你选择修改MIB的某些东西，你需要学习SMIv2和ASN.1语法，不过其他情况下你只需要在兴趣时看看他，而不必学习他。
To this day, SNMPv1 and SNMPv2c are the most commonly used, however due to the insecurity inherent to these protocols read-only access is typical. In general, don’t bother with SNMPv3 unless you really need the added security features.

1.3. 本文不涉及的话题

There are several subject we will not be discussing in this paper. These topics include writing agents or sub-agents, writing MIB modules, trap generation and trap sending, synchronous vs asynchronous SNMP coding, and MIB parsing.

Something that scares new or inexperienced coders away from the Net-SNMP documentation is the seemingly constant reference to synchronous and asynchronous applications. Don’t be afraid, thats referring to applications that can’t afford to sit and wait for a response. If your application needs a non-blocking method of handling SNMP traffic, use the asynchronous interface (eg: GUIs, Threads, Forking, etc). Otherwise, just stick with the synchronous interfaces for typical use.

Net-SNMP中关于同步和异步应用程序的文档，常常会把没有经验的编码新手给吓唬住。别担心，那只是指无法坐等响应的应用程序。如果你的应用程序需要以非阻塞方式处理SNMP数据流，就使用一步接口（例如GUI、线程、forking等）。否则，只需要使用同步接口就可以了。
Lastly, this document addresses the use of Net-SNMP on UNIX systems only. Please refer to the Net-SNMP website for information regarding development on Win32.

2. MIB和OID
OID(对象标识符），是SNMP代理提供的具有唯一标识的键值。MIB（管理信息基）提供数字化OID到可读文本的映射。
2.1. OID
OID的编写规则和习惯
SNMP OIDs are laid out in a hierarchy forming unique addresses into a tree similar to the DNS hierarchy. Like many other forms of addressing, OIDs can be used in 2 forms: fully qualified and relative (sometimes called ”relevant”).

SNMP OID是用一种按照层次化格式组织的、树状结构中的唯一地址来表示的，它与DNS层次相似。与其他格式的寻址方式类型，OID以两种格式加以应用：全名和先对名（有时称为“相关”）
The fully qualified form starts from the root and moves outward to the individual value on a device. An example of a fully qualified address is:

This OID could be rewritten in human readable form as:

All fully qualified OIDs will begin with .iso.org.dod.internet.private represented numerically as .1.3.6.1.4. Almost all OIDs will then be followed by enterprises (.1) and a unique number for the vendor as assigned by the Internet Assigned Numbers Authority (IANA). In the example OID 789 represents the vendor ID for the Network Appliance Corporation (NetApp). Everything beyond the vendor ID is based on the vendors implementation and may vary between implementations. Please note the prefixing dot before iso. Similar to the trailing dot in DNS, properly qualified IODs begin with a dot representing the root.

The complete list of enterprise assignments can be found at the IANA website: http://www.iana.org/assignments/enterprise-numbers

IANA网站上找到企业分配完整的清单 : http://www.iana.org/assignmenets/enterprise-numbers
The relative form of an OID, on the other hand, begins from the enterprises value and leaves all the implied addressing off. So we can use the relative form of the above OID as enterprises.netapp.netapp1.raid.diskSummary.diskSpareCount.0 or numerically as .1.789.1.6.4.8.0 .

OID的先对格式，从企业值开始，略过所有的隐含地址。因此，我们可以用 enterprises.netapp.netappl.raid.diskSUmmary.diskSpaceCount.0 来表示上述的OID，或者用数字格式 .1.789.6.4.8.0 .
A common form of writing OIDs is by the name of the MIB and a unique key defined within the MIB. For instance, we could rewrite the above OID into the condensed form NETWORK-APPLIANCE-MIB::diskSpareCount.0 . This condensed form follows the convention of MIB Name::Unique Key.instance. Some keys, while unique, can be represented by multiple instances of that key, and thus all OIDs end with an instance value. This is why you’ll notice that most OIDs end with a .0 .

MIB Name::唯一键值.instance.

2.2. MIB
MIB介绍
The structure of a MIBs internals are a little strange and foreign at first, but it’s structured well enough that you can poke through it pretty intelligently without really knowing what your doing. The structure of a MIB comes from the Structure of Management Information (SMI) standard detailed in IETF RFC 1155 and 2578. If you choose to modify or write your own MIBs you’ll benefit from understanding SMI before hacking much on MIBs.

MIB的内部结构刚开始时会让人感觉有些奇怪和不好理解，不过它的结构非常好，你可以在不懂的情况下一个一个看进去。MIB的结构来源于IETF RFC1155和2578定义的管理信息结构。如果你想要修改或编写自己的MIB，在动手前理解SMI非常有帮助。
Lets look at the header of a MIB to get a better idea of how they work:

-- PowerNet-MIB {iso org(3) dod(6) internet(1) private(4)

-- enterprises(1) apc(318) }

PowerNet-MIB DEFINITIONS ::= BEGIN

IMPORTS

enterprises, IpAddress, Gauge, TimeTicks FROM RFC1155-SMI

DisplayString FROM RFC1213-MIB

OBJECT-TYPE FROM RFC-1212

TRAP-TYPE FROM RFC-1215;

apc OBJECT IDENTIFIER ::= { enterprises 318 }

products OBJECT IDENTIFIER ::= { apc 1 }

apcmgmt OBJECT IDENTIFIER ::= { apc 2 }

Comments can be inserted into a MIB by prepending them with two dashes. In the header the declaration BEGIN starts off the MIB. Imports can be used to pull information from other MIBs, typically those mandated by the MIB-II standard.

The MIB lays out the structure of OID addresses starting from the enterprises value. Here the enterprise value 318 maps to ”apc” (relative address .1.318). Typically then several categories are defined. Here we see 2 categories: products (.1.318.1) and apcmgmt (.1.318.2). Notice that in the curly braces two values are specified, its parent address followed by its address. So the products identifier is parented by the apc identifier which is parented by the enterprises identifier, so on and so forth. This type of categorization and subcategorizing will typically continue on in the header of the MIB for awhile segmenting the available keys into tight subgroupings. By segmenting values out in this way it makes the available keys easier to navigate.

MIB放置从enterprise值开始的OID地址的结构。在此，enterprise值是318, 对应 "apc" (相对地址为 .1.318）。 通常之后会定义几个类别。注意在花括号间定义的两个值,其父地址后面跟一个它自己的地址。因此产品标识符有apc标识符表示，其父为enterprise标识符，以此类推。类别和自类别的类型通常跟在MIB头的后面，并且把有用的键值分割为子组。通过分段，各种值分别被列出，这样可用的值更容易浏览。
The real meat of the MIB is in the description of object types. Here’s an example of a integer key:

MIB的真正好处在于对象类型的描述。以下是一个整形键值的例子:
upsBasicOutputStatus OBJECT-TYPE

SYNTAX INTEGER {

unknown(1),

onLine(2),

onBattery(3),

onSmartBoost(4),

timedSleeping(5),

softwareBypass(6),

off(7),

rebooting(8),

switchedBypass(9),

hardwareFailureBypass(10),

sleepingUntilPowerReturn(11),

onSmartTrim(12)

}

STATUS mandatory

DESCRIPTION

"The current state of the UPS. If the UPS is unable

to determine the state of the UPS this variable is set

to unknown(1)."

::= { upsBasicOutput 1 }

Here is defined the upsBasicOutputStatus key with a return type of INTEGER. The returned integer maps to one of 12 different return values as listed. Notice that in the MIB a description of the key is provided. These descriptions can be extremely useful in determining which objects can best provide the data you want, especially if you don’t have MIB documentation supplied by the vendor.

Notice also that the last line of the object type description includes the numeric value 1 with upsBasicOutput as the parent. If we follow this parenting backwards in the MIB we’d find that upsBasicOutput has the value 1 and is parented by upsOutput which has the value 4 and is parented by ups which has a value of 1, which is parented by hardware which has a value of 1, which is parented by products with a value of 1 which is parented by apc with a value of 318, which is parented by enterprises with a value of 1. So, if we put all that mapping together we get a relative address for the key upsBasicOutputStatus of .1.318.1.1.1.4.1.1.0. Remember that the trailing .0 represents the first instance of the key. Applications called MIB Browsers can easily parse a MIB and make navigation much quicker than flipping through the file in vim, but don’t be fooled into thinking it’s difficult without such a tool.

So, whats really important to notice here is that the MIB is really just providing us with a road map of the OIDs available on the agent we wish to get values from. A MIB describes both where to find a value and what it returns. We can still interface with a device without the MIB, it’s just much easier when you get a return of ”Up” instead of ”1”. By leveraging the options of the Net- SNMP CLI tools you can decide just how you wish to return output which will be different if your just using the tool from the command line (where ”Up” is preferable) or if your calling the tool from a script (where ”1” is preferable).

2.3. OID数据类型
SMI定义的OID返回值的数据类型。
SMI defines a fixed number of datatypes which are returned by OIDs. These datatypes include:

SMI定义了一定数量的OID返回的数据类型。这些数据类型包括：
Integer
Signed 32bit Integer (values between -2147483648 and 2147483647). 有符号32位整数（值范围: -2147483648 - +2147483648）
Integer32
Same as Integer. 与Integer相同。
UInteger32
Unsigned 32bit Integer (values between 0 and 4294967295). 无符号32位整数（值范围：0－4294967295）.
Octet String
Arbitrary binary or textual data, typically limited to 255 characters in length. 任意二进制或文本数据，通常长度限制在255个字符内。
Object Identifier
An OID. 一个OID。
Bit String
Represents an enumeration of named bits. This is an unsigned datatype. 表示取名的位的枚举。这是一个无符号的数据类型。
Counter32
Represents a non-negative integer which monotonically increases until it reaches a maximum value of 32bits-1 (4294967295 dec), when it wraps around and starts increasing again from zero. 表示一个非负的整数（可递增到32位最大值－1），然后恢复并从0开始递增。
Counter64
Same as Counter32 but has a maximum value of 64bits-1. 与Counter32相同，最大值为64位的最大值－1。
Gauge32
Represents an unsigned integer, which may increase or decrease, but shall never exceed a maximum value. 表示无符号整数，可增加或减少，但是不超过最大值。
TimeTicks
Represents an unsigned integer which represents the time, modulo 2ˆ32 (4294967296 dec), in hundredths of a second between two epochs. 表示代表数据的一个无符号整数，2^32取模（4294967296），两个值之间为百分之一秒。
Opaque
Provided solely for backward-compatibility, its no longer used. 提供向下兼容，不再使用的数据类型
Represents an OSI address as a variable-length OCTET STRING. 表示一个用变长八进制字符窗表示的OSI地址。
Net-SNMP tools will report the datatype when returning an OID unless you otherwise disregard it. As an example of that you’ll see:

Net-SNMP工具在返回一个OID时会包括其数据类型，除非你不想要他。以下是一个例子：
SNMPv2-MIB::sysContact.0 = STRING: Ben Rockwood

SNMPv2-MIB::sysUpTime.0 = Timeticks: (47372422) 5 days, 11:35:24.22

SNMPv2-MIB::sysObjectID.0 = OID: SNMPv2-SMI::enterprises.318.1.3.7

RFC1213-MIB::atPhysAddress.1.1.10.10.1.1 = Hex-STRING: 00 50 73 28 47 A0

IF-MIB::ifSpeed.1 = Gauge32: 10000000

SNMPv2-MIB::snmpInPkts.0 = Counter32: 316

SNMPv2-MIB::snmpOutPkts.0 = Counter32: 314

This is a fairly typical spread of datatypes returned by Net-SNMP tools. Notice that some values are being automatically interpreted by Net-SNMP, such as the sysUpTime and ifAdminStatus. The MIB was used when these values were returned and Net-SNMP was nice enough to find the return value in the MIB and give us the textual representation of the value.

2.4. MIB II
MIB II
IETF RFC 1213 ”defines the second version of the Management Information Base (MIB-II) for use with network management protocols in TCP/IP-based internets.” All SNMP agent and tool distributions should include MIBs that will comply with MIB-II and all devices should at the very least return values that comply with the MIB-II standard.

Within the MIB-II standard several OID groups are defined, including:

The System Group
Basic system identification and information OIDs such as sysDescr, sysContact, sysName, SysLocation, etc. (Reported by Net-SNMP in SNMPv2-MIB)
The Interfaces Group
Network Interface information such as ifDescr, ifType,ifSpeed, ifAdminStatus, etc. (Reported by Net-SNMP in IF-MIB)
The IP Group
IP stats and settings such as ipInReceives, ipForwarding, ip-InAddrErrors, etc. (Reported by Net-SNMP in IP-MIB)
The ICMP Group
ICMP stats and settings such as icmpInMsgs, icmpIn-Errors, icmpInRedirects, etc. (Reported by Net-SNMP in IP-MIB)
The TCP Group
TCP stats and settings such as tcpActiveOpens, tcpPassiveOpens,tcpInErrs, etc. (Reported by Net-SNMP in TCP-MIB)
The UDP Group
UDP stats and settings such as udpInDatagrams, udpIn-Errors, etc. (Reported by Net-SNMP in UDP-MIB)
The EGP Group
EGP stats and settings (if the device support EGP) such as egpNeighAs, egpNeighMode, etc (Reported by Net-SNMP in RFC1213-MIB)
The Transmission Group
Device specific media transmition stats and settings(Reported by Net-SNMP in RFC1213-MIB or your vendor MIB)
The SNMP Group
SNMP stats and settings such as snmpInPkts, snmp-InASNParseErrs, snmpInTraps, etc. (Reported by Net-SNMP in SNMPv2-MIB)
If you do a default walk of an SNMP device the MIB-II data should be returned. All data with the exception of the EGP and Transmission groups are requirements of the standard. For most networking devices such as routers this information is usually sufficient to provide most of the information you could want.

2.5. 为Net-SNMP添加MIB

Additional MIBs can be added to your Net-SNMP installation by simply copying them into the \$(PREFIX)/share/snmp/mibs directory. MIBs should be (re)named to follow the convention (MIB NAME).txt for clarity. You can find the MIBs proper name on the first uncommented line of the MIB (eg: Name- MIB DEFINITIONS ::= BEGIN).

For example, if you downloaded MIB for the JetDirect Management Card found on HP LaserJet printers it might have been named something like ”hpjetdirect. mib”. The header of the MIB looks like the following:

-- (C) COPYRIGHT HEWLETT-PACKARD COMPANY 1997.

-- LaserJet 5Si Printer Model Specific MIB.

--

LaserJet5Si-MIB DEFINITIONS ::= BEGIN

This MIB should be renamed to ”LaserJet5Si-MIB.txt” and copied into the Net-SNMP mibs/ directory.

By following this convention it assures greater clarity when utilizing the various MIBs and a consistency with all other installed MIBs.

MIBs can be specified by a command line tool using the -m argument or the MIBS environmental variable for libsnmp applications including the PERL module. MIBs can be referenced locally by supplying a proper path (ie: - m ”./MY MIB.txt”) or globally by supplying the MIB name without the .txt suffix (ie: -m ”MY MIB”) if it’s located in the Net-SNMP MIBs directory.

• 写评论