简体   繁体   English

用python easysnmp捕获异常

[英]catching exceptions with python easysnmp

I cannot seem to find documentation or examples of how to catch exceptions with Python's easySNMP library 我似乎找不到使用Python的easySNMP库捕获异常的文档或示例

https://easysnmp.readthedocs.io/en/latest/exceptions.html shows what exceptions are rasied but I get errors when trying to catch them https://easysnmp.readthedocs.io/zh-CN/latest/exceptions.html显示了哪些异常被引发,但是尝试捕获它们时出现错误

Simplified code: 简化代码:

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")

Output: 输出:

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

Your error says name 'easysnmp' is not defined. 您的错误name 'easysnmp' is not defined.

That is because you haven't imported it. 那是因为您还没有导入它。

Instead you imported from easysnmp import Session 相反,您是from easysnmp import Session

you need to do import easysnmp 您需要import easysnmp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM