- Hands-On Enterprise Automation with Python.
- Bassem Aly
- 226字
- 2021-06-18 19:22:34
Exception handling in netmiko
When we design our Python script, we assume that the device is up and running and also that the user has provided the correct credentials, which is not always the case. Sometimes there's a network connectivity issue between Python and the remote device or the user enters the wrong credentials. Usually, python will throw an exception if this happens and will exit, which is not the optimum solution.
The exception handling module in netmiko, netmiko.ssh_exception, provides some exception classes that can handle such situations. The first one is AuthenticationException, and will catch the authentication errors in the remote device. The second class is NetMikoTimeoutException, which will catch timeouts or any connectivity issues between netmiko and the device. What we will need to do is wrap our ConnectHandler() method with the try-except clause and catch timeout and authentication exceptions:
from netmiko import ConnectHandler
from netmiko.ssh_exception import AuthenticationException, NetMikoTimeoutException
device = {
'device_type': 'cisco_ios',
'ip': '10.10.88.112',
'username': 'admin',
'password': 'access123',
'secret': 'access123',
}
print "########## Connecting to Device {0} ############".format(device['ip'])
try:
net_connect = ConnectHandler(**device)
net_connect.enable()
print "***** show ip configuration of Device *****"
output = net_connect.send_command("show ip int b")
print output
net_connect.disconnect()
except NetMikoTimeoutException:
print "=========== SOMETHING WRONG HAPPEN WITH {0} ============".format(device['ip'])
except AuthenticationException:
print "========= Authentication Failed with {0} ============".format(device['ip'])
except Exception as unknown_error:
print "============ SOMETHING UNKNOWN HAPPEN WITH {0} ============"
- FuelPHP Application Development Blueprints
- Cocos2D-X權威指南(第2版)
- Java系統分析與架構設計
- 單片機C語言程序設計實訓100例:基于STC8051+Proteus仿真與實戰
- Python零基礎快樂學習之旅(K12實戰訓練)
- SQL語言從入門到精通
- TypeScript實戰指南
- OpenCV 4計算機視覺項目實戰(原書第2版)
- Oracle GoldenGate 12c Implementer's Guide
- Julia 1.0 Programming Complete Reference Guide
- JSP程序設計實例教程(第2版)
- App Inventor少兒趣味編程動手做
- R語言數據挖掘:實用項目解析
- Python物理建模初學者指南(第2版)
- Flink入門與實戰