1. 获取SNMP变量
复制和粘贴下列代码到Python命令提示符上,代码将会执行SNMP GET操作获取sysDescr.0对象,这是一个公开可用的SNMP Command Responder, 更多对象请参考demo.snmplabs.com
“”"
SNMPv1
++++++
Send SNMP GET request using the following options:
- 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,
Functionally similar to:
| $ 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在这里插入代码片
2. 发送SNMP TRAP
想给demo.snmplabs.com中列出的宿主Notification Receiver发送TRAP消息,复制以下代码到你的交互式Python会话中。
`"""
SNMPv1 TRAP with defaults
+++++++++++++++++++++++++
Send 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)
许多ASN.1 MIB文件可以通过mibs.snmplabs.com进行下载,也可以配置PySNMP自动下载他们。在这里插入代码片`
.引自添加链接描述