Adam Walker
Adam Walker

Reputation: 56

Python - SSH to list of IP addresses. Exception handling on Connection Timeout

I am having an issue handling a timeout error in Paramiko. Below is similar to what I am using to connect.

try:
    dssh = paramiko.SSHClient()
    dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    dssh.connect(IP, username, password)  
    stdin, stdout, stderr = dssh.exec_command('sho run')
    status = 'success'
except paramiko.AuthenticationException:
    status = 'fail'

When a host is down I get an error such as the one below and the script aborts.

Traceback (most recent call last):
  File "ssh3.py", line 23, in <module>
    dssh.connect(IP, username, password)
  File "/usr/lib/python2.7/site-packages/paramiko/client.py", line 296, in connect
    sock.connect(addr)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 116] Connection timed out

Is there a way to catch this error and allow the script to run beginning to end?

Upvotes: 0

Views: 2217

Answers (1)

Thomas Orozco
Thomas Orozco

Reputation: 55303

Surely. You just need to catch the exception that is being raised.

# At the beginning of your code:
import socket

# In your loop
try:
    # Your stuff
# Replace the existing exception handler:
except (socket.error, paramiko.AuthenticationException):
    status = 'fail'

Upvotes: 3

Related Questions