I'm writing a script in Python that pulls configurations from Cisco routers using Paramiko for the SSH connection. I am also trying to make it verify that the login credentials are correct for the device without failing.
Right now the code will connect and run the commands that I want if the credentials are correct. GREAT! However if I feed it 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()
Once I have started the program and fed it the wrong credentials this is the output.
paramiko.AuthenticationException: Authentication failed.
This I know that the credentials are wrong but I don't want the script to just fail, I would like it to make display the problem and continue running the rest of the script.
Any ideas?
Take a look at section 8.3 (handling exceptions) on the Python manual. You can "catch" the exception and handle it, this will prevent the exception from causing your program to exit. Your program will only exit on an exception if no code catches 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'll have to write your code so that it doesn't fail if shell
is None
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With