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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值