当前位置:   article > 正文

python 使用 pysnmp 采集 SNMP 数据

pysnmp
  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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  1. pysnmp 参数文档
http://ports.gnu-darwin.org/net-mgmt/py-snmp4/work/pysnmp-4.1.7a/docs/pysnmp-tutorial.html#UsmUserData
# 源码中注释比较详细,可直接参看源码中注释
  • 1
  • 2
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/156710
推荐阅读
相关标签
  

闽ICP备14008679号