Ajwad Ibrahim
Ajwad Ibrahim

Reputation: 127

Catch AuthenticationException in Python Paramiko

import paramiko

host='x.x.x.x'
port=22
username='root'
password='password'

cmd='dmidecode > a' 

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host,port,username,password)
try:
    stdin,stdout,stderr=ssh.exec_command(cmd)
    outlines=stdout.readlines()
    resp=''.join(outlines)
    print(resp)
except paramiko.AuthenticationException as error:
    print "ERROR"

I'm unable to catch the AuthenticationException. Can anyone suggest me any other way to not break the script and only display the error?

Upvotes: 1

Views: 14233

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202292

AuthenticationException happens in SSHClient.connect:

Raises: AuthenticationException – if authentication failed

And your SSHClient.connect call is not in your try block.

This should work:

try:
    ssh.connect(host,port,username,password)
    stdin,stdout,stderr=ssh.exec_command(cmd)
    outlines=stdout.readlines()
    resp=''.join(outlines)
    print(resp)
except paramiko.AuthenticationException as error:
    print "ERROR"

Upvotes: 4

Related Questions