Python使用PySNMP获取交换机名

使用的SNMPv2c。

源码来自http://snmplabs.com/pysnmp/examples/hlapi/asyncore/sync/manager/cmdgen/snmp-versions.html

做了一点修改。

# -*- coding: utf-8 -*-
from pysnmp.hlapi import *

deviceIP = "192.168.75.137"
snmpv2Community = "testv2"

# ----------------------------------------------------------------

def getDeviceName(deviceIP, snmpCommunity):   
    deviceNameOID = "1.3.6.1.2.1.1.5.0"
    
    errorIndication, errorStatus, errorIndex, varBinds = next(
        getCmd(SnmpEngine(),
               CommunityData(snmpCommunity),
               UdpTransportTarget((deviceIP, 161)),
               ContextData(),
               ObjectType(ObjectIdentity(deviceNameOID))
               )
    )

    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]))

def main():
    getDeviceName(deviceIP, snmpv2Community)

main()


# 输出结果:SNMPv2-MIB::sysName.0 = R1.test.com
发布了31 篇原创文章 · 获赞 11 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/MrRight17/article/details/84455274