首页 > 解决方案 > 使用 Python pysnmp 拉取交换机 SNMP 社区列表

问题描述

下面的代码适用于其他 OID,例如主机名 (1.3.6.1.2.1.1.5.0),但是我无法提取 SNMP 社区表(snmp 的允许 ips 列表)。

我在http://www.mibdepot.com/中搜索了 cisco 的“社区”,发现了 5 个 OID。所有这些都没有拉任何东西:.1.3.6.1.4.1.224.2.3.6.3.1 .1.3.6.1.4.1.224.2.3.6.1.0 .1.3.6.1.4.1.224.2.3.6.3 .1.3.6.1.4.1 .224.2.3.6.4.1 .1.3.6.1.4.1.224.2.3.6.4

对此的任何指导将不胜感激。谢谢!

from pysnmp import hlapi

def get(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()):
    handler = hlapi.getCmd(
        engine,
        credentials,
        hlapi.UdpTransportTarget((target, port)),
        context,
        *construct_object_types(oids)
    )
    return fetch(handler, 1)[0]
    
def construct_object_types(list_of_oids):
    object_types = []
    for oid in list_of_oids:
        object_types.append(hlapi.ObjectType(hlapi.ObjectIdentity(oid)))
    return object_types
    
def fetch(handler, count):
    result = []
    for i in range(count):
        try:
            error_indication, error_status, error_index, var_binds = next(handler)
            if not error_indication and not error_status:
                items = {}
                for var_bind in var_binds:
                    items[str(var_bind[0])] = cast(var_bind[1])
                result.append(items)
            else:
                raise RuntimeError('Got SNMP error: {0}'.format(error_indication))
        except StopIteration:
            break
    return result
    
def cast(value):
    try:
        return int(value)
    except (ValueError, TypeError):
        try:
            return float(value)
        except (ValueError, TypeError):
            try:
                return str(value)
            except (ValueError, TypeError):
                pass
    return value

def getSNMPCommunities(ip):
    try:
        communities = get(ip, ['1.3.6.1.4.1.224.2.3.6.1.0'], hlapi.CommunityData('public'))
        return communities.get('1.3.6.1.4.1.224.2.3.6.1.0')
    except:
        return None
        
snmpCommunities = getSNMPCommunities('10.0.0.1')
print(type(snmpCommunities))
print(snmpCommunities)

标签: pythonpysnmp

解决方案


这是不可能的,因为 SNMP 只读不应该有权访问此信息。

我想出的解决方案是通过 SSH 登录并读取标准输出。


推荐阅读