官术网_书友最值得收藏!

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} ============"
主站蜘蛛池模板: 柏乡县| 广西| 唐山市| 江安县| 吉木乃县| 庄河市| 双鸭山市| 赣榆县| 五常市| 巴林左旗| 繁峙县| 阳曲县| 永宁县| 确山县| 垦利县| 嵩明县| 浦北县| 汤原县| 滦南县| 汉川市| 睢宁县| 西畴县| 九江县| 密山市| 洛南县| 禹州市| 清水县| 铜山县| 罗田县| 高唐县| 正阳县| 门头沟区| 大余县| 扶绥县| 余庆县| 察哈| 明溪县| 百色市| 武胜县| 屏山县| 深圳市|