Operation and maintenance of the juvenile series python and cisco (3)

Operation and maintenance of the juvenile series python and cisco (3)

Exception Handling

What is Exception Handling?

Exception handling is usually in the implementation of various programs (non compile time) appearing error processing, if there is no exception handling, then when it goes wrong, the entire program will exit immediately after done exception handling, program error handling will be based on the definition of abnormal way.

Popular terms: If no exception handler, the program that goes wrong on the GG

Series common exceptions

This series of articles common abnormality, what does?

  • Connection failed

The reason there are many failed connection, such as network unreasonable matter, the port did not open it ...

Connection failure exception thrown as follows

[root@yunwei cisco]# python ywsn_p_c_lab3.py 
Traceback (most recent call last):
  File "ywsn_p_c_lab3.py", line 9in <module>
    s.connect(ip,username=user,password=passwd,look_for_keys=False,allow_agent=False)
  File "/usr/lib/python2.7/site-packages/paramiko/client.py", line 362in connect
    raise NoValidConnectionsError(errors)
paramiko.ssh_exception.NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 192.168.200.2
[root@yunwei cisco]

When do exception handling, we need to focus on what is it? An exception is thrown in the code, such as hereparamiko.ssh_exception.NoValidConnectionsError

How do exception handling? Exception handling in python used try:... expect..., such as

import paramiko
import time
user = 'yunwsn'
passwd = '123456'
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
IP = file('IP.txt','rb')

for ip in IP.xreadlines():
    try:  # 异常处理以下内容
        s.connect(ip,username=user,password=passwd,look_for_keys=False,allow_agent=False)  # 如果这里出现异常,那么直接到execpt代码块中去了,不会打印下面的成功
        print '[ \033[0;32m success\033[0m ] login %s ' %ip

    except paramiko.ssh_exception.NoValidConnectionsError:
        print '[ \033[0;32m failed \033[0m ] Unable to connect to %s ' % ip


IP.close()

Running about (moving map)

  • socket timeout

Abnormal follows, sometimes due to poor quality or IP network does not exist, resulting in socket connection timeout (any connections are socket-based), the following exception

Traceback (most recent call last):
  File "ywsn_p_c_lab3.py", line 11in <module>
    s.connect(ip,username=user,password=passwd,look_for_keys=False,allow_agent=False)
  File "/usr/lib/python2.7/site-packages/paramiko/client.py", line 343in connect
    retry_on_signal(lambda: sock.connect(addr))
  File "/usr/lib/python2.7/site-packages/paramiko/util.py", line 280in retry_on_signal
    return function()
  File "/usr/lib/python2.7/site-packages/paramiko/client.py", line 343in <lambda>
    retry_on_signal(lambda: sock.connect(addr))
  File "/usr/lib64/python2.7/socket.py", line 224in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 110Connection timed out

Here is the code throws an exception socket.error, you can see this is socketbeing given module, if we are to deal with this anomaly, then you need to import socketthe module can.

  • Authentication failed

Since we are using in this series is ssh way, so there will be the process of verification, validation failure is so common an unusual way.

Look authentication failure exceptions thrown

  File "ywsn_p_c_lab3.py", line 11in <module>
    s.connect(ip,username=user,password='123',look_for_keys=False,allow_agent=False)
  File "/usr/lib/python2.7/site-packages/paramiko/client.py", line 437in connect
    passphrase,
  File "/usr/lib/python2.7/site-packages/paramiko/client.py", line 749in _auth
    raise saved_exception
paramiko.ssh_exception.AuthenticationException: Authentication failed.

So what is it abnormal code here? It must be paramiko.ssh_exception.AuthenticationException: Authentication failed.friends ~

Here's how to do exception handling I do not say it! You can refer to the above to test yourself.

Topology Description

  • Topology

  • Explanation

I will write in IP.txt in four IP, two in the topology map, a the other two are not, network unreasonable, timeouts, authentication fails, everything is ok with the three cases.

Implementation code

In order to facilitate everyone to see here, I put all exceptions apart, in fact, put together is also possible. The following annotate the new code, the remaining code comments can view the first two articles.

import paramiko
import socket  # 导入socket模块
import time 
user = 'yunwsn'
passwd = '123456'
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
IP = file('IP.txt','rb')

for ip in IP.xreadlines():
    try:  # 异常处理
        s.connect(ip,username=user,password=passwd,timeout=5,look_for_keys=False,allow_agent=False)
        print '[ \033[0;32m success\033[0m ] login %s ' %ip
        cmd = s.invoke_shell()
        cmd.send('show ip int bri \n  ')
        time.sleep(0.1)
        output = cmd.recv(65535)
        print output
        cmd.close()
    except paramiko.ssh_exception.NoValidConnectionsError: # 网络/端口不通异常
        print '[ \033[0;31m failed \033[0m ] Unable to connect to %s ' % ip
    except socket.error,err:  # 超时异常,err代表异常代码之后的提示
        print '[ \033[0;31m failed \033[0m ] %s to %s' %(err,ip)
    except paramiko.ssh_exception.AuthenticationException: # 验证失败的异常
        print '[ \033[0;31m failed \033[0m ] Authentication failed on %s' % ip

IP.close()
  • IP.txt

192.168.108.252
192.168.108.253
192.168.108.254
192.168.108.251
  • Operating results (FIG movable)

Micro-channel public number: operation and maintenance teenager


Guess you like

Origin blog.51cto.com/xiaowangzai/2406527