用python easysnmp捕获异常

时间:2018-11-26 13:31:09

标签: python snmp easysnmp

我似乎找不到使用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

1 个答案:

答案 0 :(得分:1)

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

那是因为您尚未导入它。

相反,您导入了from easysnmp import Session

您需要做import easysnmp