Parametric authentication (it turns out that Python exception handling)

I am writing a script in Python that retrieves configurations from Cisco routers using Paramiko to connect SSH. I am also trying to make sure the login credentials are correct for the device without crashing.

Currently, the code will connect and run the commands that I want if the credentials are correct. GREAT! However, if I give him the wrong credentials, the script fails with an authentication error.

The code:

ip = *.*.*.* u = username p = password ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=u, password=p) shell = ssh.invoke_shell() 

As soon as I run the program and gave it the wrong credentials, this is the result.

paramiko.AuthenticationException: Authentication failed.

I know that the credentials are incorrect, but I don’t want the script to simply fail, I would like it to display the problem and continue working with the rest of the script.

Any ideas?

+6
source share
1 answer

Take a look at section 8.3 (exception handling) in the Python manual . You can catch the exception and handle it, this will prevent the exception from being thrown from your program. Your program will only exit the exception if the code does not catch it.

 try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=u, password=p) shell = ssh.invoke_shell() except paramiko.AuthenticationException: print "We had an authentication exception!" shell = None 

However, you will have to write your code so that it does not fail if the shell is None .

+7
source

Source: https://habr.com/ru/post/890679/


All Articles