如何使用PySNMP获取SNMPtable

2024-06-30 16:56:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从CDP表中获取关于设备邻居的信息,但是我只得到一个邻居的数据。例如,我确定设备有两个邻居,我向cdpCacheDeviceId发出请求,得到一个邻居的ID。如何获取两个设备的ID?在

def get_cdp_tables(host):
for (errorIndication,
     errorStatus,
     errorIndex,
     varBinds) in nextCmd(SnmpEngine(),
                          CommunityData(''),
                          UdpTransportTarget((host, 161)),
                          ContextData(),
                          # cdpCacheTable
                          ObjectType(ObjectIdentity('1.0.8802.1.1.2.1.4.1.1.7')),  # cdpCacheDevicePort
                          ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.23.1.2.1.1.17')),  # cdpCacheSysName
                          ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.23.1.2.1.1.1')),  # cdpCacheIfIndex
                          ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.23.1.2.1.1.6')),  # cdpCacheDeviceId
                          ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.23.1.2.1.1.4')),  # cdpCacheAddress
                          lexicographicMode=False):

    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        with open('cdp.txt', 'a', 1) as cdp_file:
            cdp_file.write(host + '\n')
            for i in range(len(varBinds)):
                cdp_file.write(str(varBinds[i]) + '\n')
        return

这就是我在输出中得到的:

^{pr2}$

Tags: inidhostforfilewriteprintcdp
1条回答
网友
1楼 · 发布于 2024-06-30 16:56:02

正如伊利亚·埃蒂戈夫所说,这里有一个问题,{}与不正确的表格。工作代码如下:

def get_cdp_tables(host):
for (errorIndication,
     errorStatus,
     errorIndex,
     varBinds) in nextCmd(SnmpEngine(),
                          CommunityData(''),
                          UdpTransportTarget((host, 161)),
                          ContextData(),
                          # cdpCacheTable
                          ObjectType(ObjectIdentity('1.0.8802.1.1.2.1.4.1.1.7')),  # cdpCacheDevicePort
                          ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.23.1.2.1.1.17')),  # cdpCacheSysName
                          ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.23.1.2.1.1.1')),  # cdpCacheIfIndex
                          ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.23.1.2.1.1.6')),  # cdpCacheDeviceId
                          ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.23.1.2.1.1.4')),  # cdpCacheAddress
                          lexicographicMode=False):

    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        with open('cdp.txt', 'a', 1) as cdp_file:
            cdp_file.write(host + '\n')
            for i in range(len(varBinds)):
                cdp_file.write(str(varBinds[i]) + '\n')
return

相关问题 更多 >