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

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个通过pysnmp模块获取交换机某个接口速率的Python脚本: ```python from pysnmp.hlapi import * # 设置SNMP参数 ip_address = '交换机IP地址' community = 'SNMP Community字符串' port = 161 # 定义OID if_speed_oid = '.1.3.6.1.2.1.2.2.1.5' # 接口速率 if_name_oid = '.1.3.6.1.2.1.31.1.1.1.1' # 接口称 # 获取接口称和速率 def get_interface_speed(interface_name): # 创建SNMP请求 iterator = getCmd( SnmpEngine(), CommunityData(community), UdpTransportTarget((ip_address, port)), ContextData(), ObjectType(ObjectIdentity(if_speed_oid, interface_name)), ObjectType(ObjectIdentity(if_name_oid, interface_name)) ) # 解析SNMP响应 for errorIndication, errorStatus, errorIndex, varBinds in iterator: if errorIndication: print(errorIndication) return None elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) return None else: # 获取接口速率 if_speed = int(varBinds[0][1]) # 获取接口称 if_name = varBinds[1][1].prettyPrint() return (if_name, if_speed) # 测试 if_name, if_speed = get_interface_speed('GigabitEthernet0/0/1') if if_name and if_speed: print('接口称:%s,速率:%d' % (if_name, if_speed)) else: print('获取接口速率失败') ``` 在脚本中,我们首先设置了SNMP参数,包括交换机IP地址、SNMP Community字符串和SNMP端口。然后,我们定义了两个OID,一个是接口速率的OID,另一个是接口称的OID。接着,我们定义了一个函数`get_interface_speed`,用于获取指定接口的速率和称。在函数中,我们使用`getCmd`函数创建了一个SNMP请求,并指定了要获取的两个OID。然后,我们解析SNMP响应,获取接口速率和称,并返回一个包含这两个值的元组。最后,我们调用`get_interface_speed`函数获取指定接口的速率和称,并打印输出。 需要注意的是,使用pysnmp模块获取交换机接口速率时,需要确保交换机已开启SNMP,并且设置了正确的SNMP Community字符串。同时,需要根据交换机的具体情况修改脚本中的IP地址和OID。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值