0

我似乎找不到有关如何使用 Python 的 easySNMP 库捕获异常的文档或示例

https://easysnmp.readthedocs.io/en/latest/exceptions.html显示引发了哪些异常,但在尝试捕获它们时出现错误

简化代码:

from easysnmp import Session
try:
    session = Session(hostname=host,community=community, version=2)
except:
    print("ERROR - SNMP error:")
    sys.exit(3)    

def check_snmp(oid):
    try:
        ret = session.get(oid).value
    except easysnmp.EasySNMPNoSuchInstanceError:
        ## Return false if OID doesn't exists
        return 0
    except session.EasySNMPError as e:
        ## Print the error on general errors
        print("ERROR - SNMP error: {}".format(e))
    return 1

if check_snnp('ifalias.4'):
    print("SNMP returned true")

输出:

Traceback (most recent call last):
    File "./check_ip_route", line 72, in <module>
    if check_snmp(oid):
    File "./check_snmp", line 45, in check_snmp
        except easysnmp.EasySNMPNoSuchInstanceError:
    NameError: name 'easysnmp' is not defined
4

1 回答 1

1

你的错误说name 'easysnmp' is not defined.

那是因为你还没有导入它。

相反,您导入了from easysnmp import Session

你需要做import easysnmp

于 2018-11-26T13:35:29.847 回答