pysnmp 快速入门 简单测试代码

文档转载自:
http://pysnmp.sourceforge.net/quick-start.html#fetch-snmp-variable

Quick start

Once you downloaded and installed PySNMP library on your Linux/Windows/OS X system, you should be able to solve the very basic SNMP task right from your Python prompt - fetch some data from a remote SNMP Agent (you’d need at least version 4.3.0 to run code from this page).

Fetch SNMP variable

So just cut&paste the following code right into your Python prompt. The code will performs SNMP GET operation for a sysDescr.0 object at a publically available SNMP Command Responder at demo.snmplabs.com:
http://snmplabs.com/snmpsim/index.html
http://snmpsim.sourceforge.net/public-snmp-simulator.html

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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]))

If everything works as it should you will get:

...
SNMPv2-MIB::sysDescr."0" = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m
>>>

或者是

SNMPv2-MIB::sysDescr.0 = Linux zeus 4.8.6.5-smp #2 SMP Sun Nov 13 14:58:11 CDT 2016 i686

on your console.

Send SNMP TRAP

To send a trivial TRAP message to our hosted Notification Receiver at demo.snmplabs.com , just cut&paste the following code into your interactive Python session:

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)

Many ASN.1 MIB files could be downloaded from mibs.snmplabs.com or PySNMP could be configured to download them automatically.

For more sophisticated examples and use cases please refer to examples and library reference pages.

阅读更多

没有更多推荐了,返回首页