python 使用 pysnmp 采集 SNMP 数据

  1. 带加密参数,超时时间,重试次数
from pysnmp.hlapi import UsmUserData, usmHMACSHAAuthProtocol, UdpTransportTarget, usmDESPrivProtocol, \
    usmAesCfb128Protocol

from pysnmp.entity.rfc3413.oneliner import cmdgen


def get_oid_value(username, auth_key, priv_key, host, oid):
    cg = cmdgen.CommandGenerator()
    iterator = cg.getCmd(
                      UsmUserData(username, auth_key, priv_key,
                                  usmHMACSHAAuthProtocol, usmAesCfb128Protocol),
                      UdpTransportTarget((host, 161), timeout=10, retries=1),
                      oid)

    errorIndication, errorStatus, errorIndex, varBinds = iterator

    if errorIndication:  # SNMP engine errors
        print("errorIndication", errorIndication)
    else:
        if errorStatus:  # SNMP agent errors
            print('%s at %s' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] if errorIndex else '?'))
        else:

            for varBind in varBinds:  # SNMP response contents
                print([x.prettyPrint() for x in varBind])
            print(varBinds[0][1])
            return varBinds[0][1]

  1. 无加密,简单版本
from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
    cmdgen.CommunityData('public'),
    cmdgen.UdpTransportTarget(('localhost', 161)),
    '1.3.6.1.2.1.1.1.0',
    '1.3.6.1.2.1.1.6.0'
)

# Check for errors and print out results
if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBinds[int(errorIndex)-1] or '?'
            )
        )
    else:
        for name, val in varBinds:
            print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
  1. pysnmp 参数文档
http://ports.gnu-darwin.org/net-mgmt/py-snmp4/work/pysnmp-4.1.7a/docs/pysnmp-tutorial.html#UsmUserData
# 源码中注释比较详细,可直接参看源码中注释
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值