22

I have a code where im looping through hosts list and appending connections to connections list, if there is a connection error, i want to skip that and continue with the next host in the hosts list.

Heres what i have now:

def do_connect(self):
    """Connect to all hosts in the hosts list"""
    for host in self.hosts:
        try:
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2)
        except:
            pass
            #client.connect(host['ip'], port=int(host['port']), username=host['user'], password=host['passwd'])

        finally:
            if paramiko.SSHException():
                pass
            else:
                self.connections.append(client)

This does not work properly, if connection fails it just loops the same host again and again forever, till it establishes connection, how do i fix this?

4
  • 3
    Use continue. Commented Oct 9, 2017 at 8:45
  • 1
    I cannot understand why it will loop the same host forever? Commented Oct 9, 2017 at 8:47
  • I am not seeing any code that loops same host again Commented Oct 9, 2017 at 8:48
  • 1
    but it does, say i have host1, host2 in the hosts list, if connection to host1 cannot be established, it will for some reason keep trying to loop the same host1 again and again. Commented Oct 9, 2017 at 8:53

2 Answers 2

19

Your own answer is still wrong on quite a few points...

import logging
logger = logging.getLogger(__name__)

def do_connect(self):
    """Connect to all hosts in the hosts list"""
    for host in self.hosts:
        # this one has to go outside the try/except block
        # else `client` might not be defined.
        client = paramiko.SSHClient()
        try:
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2)

        # you only want to catch specific exceptions here
        except paramiko.SSHException as e:
            # this will log the full error message and traceback
            logger.exception("failed to connect to %(ip)s:%(port)s (user %(user)s)", host) 

            continue
        # here you want a `else` clause not a `finally`
        # (`finally` is _always_ executed)
        else:
            self.connections.append(client)
Sign up to request clarification or add additional context in comments.

2 Comments

i was getting timeout error aswell due to 2sec timeout timer, so had to import socket.timeout to get it to work properly, otherwise this works. Accepted answer
Isn't the continue superfluous given the else and no additional code after the try block?
4

Ok, got it working, i needed to add the Continue, mentioned by Mark and also the previous if check inside finally was always returning true so that was fixed aswell.

Here is the fixed code, that doesnt add failed connections and continues the loop normally after that:

def do_connect(self):
    """Connect to all hosts in the hosts list"""
    for host in self.hosts:
        try:
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2)
        except:
            continue
            #client.connect(host['ip'], port=int(host['port']), username=host['user'], password=host['passwd'])

        finally:
            if client._agent is None:
                pass
            else:
                self.connections.append(client)

1 Comment

You should only catch specific exceptions (connections errors in your case), and always log them (so you can check whether something wrong happened). Also you want to put the client instanciation outside the try/except block (else if it fails on the first host client will not be defined and you'll get a NameError in the finally block), and fwiw this should NOT be a finally block at all but a else block (which will be executed only if no exception occured).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.