Victory
Victory

Reputation: 131

paramiko exception for connection refused

import paramiko
try:
    ssh =paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname='10.10.1.0',username='test',password='test1234')
    print 'Successfully connected'
except paramiko.AuthenticationException:
    print "Authentication failed, please verify your credentials"
except paramiko.SSHException as sshException:
    print "Unable to establish SSH connection: %s" % sshException

This is my code. It was working fine. If i give wrong userid and password - Perfectly throwing expection.

But when hostname is not valid, it's throwing error as "Connection refused" and not sure what type of exception have to raise. Could some please help.

Error

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 290, in connect
    sock.connect(addr)
  File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused

Upvotes: 0

Views: 3146

Answers (2)

Gopal Kildoliya
Gopal Kildoliya

Reputation: 649

Use this

import errno

try:
    # Do something
except socket.error, v:
    e_code = v[0]
    if e_code == errno.ECONNREFUSED:
        print "Connection Refused"

Upvotes: 0

doctorlove
doctorlove

Reputation: 19252

socket.error is spelled socket_error like this:

from socket import error as socket_error

and then:

try:
    # as you were
except socket_error as socket_err:
    # do something

The error message is telling you about error numbers (socket_err.errno) so you can check that e.g. compare to errno.ECONNREFUSED.

Upvotes: 1

Related Questions