使用 python easysnmp 捕获异常
catching exceptions with python 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
您的错误显示 name 'easysnmp' is not defined.
那是你没有导入。
您导入了 from easysnmp import Session
你需要做import 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
您的错误显示 name 'easysnmp' is not defined.
那是你没有导入。
您导入了 from easysnmp import Session
你需要做import easysnmp