gpt4 book ai didi

python - 是否可以从该表中提取接口(interface)名称和接口(interface)状态?

转载 作者:行者123 更新时间:2023-12-01 06:40:55 26 4
gpt4 key购买 nike

最终,我希望能够得到以下格式的输出:

“接口(interface)已启动”

输出为:

['IF-MIB::ifDecr.1 = lo', 'IF-MIB::ifOperStatus.1 = up']

['IF-MIB::ifDecr.2 = eth0', 'IF-MIB::ifOperStatus.2 = up']

代码:

from pysnmp.hlapi import *

for errorIndication,errorStatus,errorIndex,varBinds in nextCmd(SnmpEngine(), \
CommunityData('public', mpModel=0), \
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')),
lexicographicMode=False):

table = []
for varBind in varBinds:
table.append(varBind.prettyPrint().strip())
for i in table:
if i not in table:
table.append(i)
print(table)
for varBind in varBinds:
table.append(varBind.prettyPrint().strip())
for i in table:
if i not in table:
table.append(i)
print(table)

最佳答案

解析的 PySNMP ObjectType 由一个 ObjectIdentity 和一个属于有效 SNMP 类型的值组成,该类型也称为 objectSyntax PySNMP。您可以使用 Python 的标准索引访问这些元素。

在您的循环中,varBinds 是一个列表,其中包含与您传递给 的两个 ObjectIdentity 相对应的完全解析的 ObjectType >nextCmd。您可以解压 varBinds 以反射(reflect)每个 objectType,然后对每个对象进行索引以获取 objectSyntax。当您调用其 prettyPrint 方法时,您将获得我们习惯的人类可读的字符串。

from pysnmp.hlapi import *

for _, _, _, varBinds in nextCmd(
SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')),
lexicographicMode=False):
descr, status = varBinds # unpack the list of resolved objectTypes
iface_name = descr[1].prettyPrint() # access the objectSyntax and get its human-readable form
iface_status = status[1].prettyPrint()
print("Interface {iface} is {status}"
.format(iface=iface_name, status=iface_status))

关于python - 是否可以从该表中提取接口(interface)名称和接口(interface)状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59460269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com