开发者

Paramiko Authentication verification (turns out to be Python exception handling)

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 wou开发者_Go百科ld 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜