快速开始
只要你安装了PySNMP库在你的Linux/Windows/OS X系统上,那么,你应该能够通过PySNMP完成一些基本的操作,比如从远端SNMP agent上获取一些数据。
获取SNMP variable
现在,复制并粘贴以下代码到你的Python环境中去运行。此代码片段对远程agent主机的sysDescr.0对象使用了SNMP GET操作,并获取结果。
"""
SNMPv1
++++++
发送 SNMP GET 请求:
* with SNMPv1, community 'public'
* over IPv4/UDP
* to an Agent at demo.snmplabs.com:161
* for two instances of SNMPv2-MIB::sysDescr.0 MIB object,
相当于使用如下命令
| $ snmpget -v1 -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0
"""#
from pysnmp.hlapi import *
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
成功运行后,得到的结果,大致如下:
SNMPv2-MIB::sysDescr."0" = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m
发送SNMP TRAP
发送一条trap消息到SNMP管理器,这里也时demo.snmplabs.com(当然可以换成你的SNMP节点的IP或域名),复制粘贴如下代码:
"""
发送 SNMPv1 TRAP through unified SNMPv3 message processing framework
using the following options:
* SNMPv1
* with community name 'public'
* over IPv4/UDP
* send TRAP notification
* with Generic Trap #1 (warmStart) and Specific Trap 0
* with default Uptime
* with default Agent Address
* with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2
* include managed object information '1.3.6.1.2.1.1.1.0' = 'my system'
Functionally similar to:
| $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s "my system"
"""#
from pysnmp.hlapi import *
errorIndication, errorStatus, errorIndex, varBinds = next(
sendNotification(
SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget(('demo.snmplabs.com', 162)),
ContextData(),
'trap',
NotificationType(
ObjectIdentity('1.3.6.1.6.3.1.1.5.2')
).addVarBinds(
('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'),
('1.3.6.1.2.1.1.1.0', OctetString('my system'))
)
)
)
if errorIndication:
print(errorIndication)
在mibs.snmplabs.com里边可以下载许多的ASN.1 MIB文件,当然也可以配置自动下载
更多的用例请参照examples和library reference。