Suedish
Suedish

Reputation: 385

How to handle socket "connection refused" exceptions in Python?

I'm just learning python and I've got a noobquestion here. What I want to do is loop the given IP addresses (192.168.43.215 through .218) and run given commands. The first host works as it can connect, while the second (.216) cannot be connected to and then the script exits with a "socket.error: [Errno 111] Connection refused" error.

I don't want it to exit the script, but to keep running on the remaining hosts. So how do I handle this exception to keep the for loop running?

#!/usr/bin/python
import socket
import sys
usernames = ["root", "admin", "robot", "email"]

for host in range(215,218):
        ipaddress = "192.168.43." + str(host)
        print ipaddress

        # Create a socket
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(10)
        # Connect to the server
        connect=s.connect((ipaddress,25))
        # Receieve the banner
        banner=s.recv(1024)
        print banner

        for x in usernames:
                # Verify a user
                s.send('VRFY ' + x + '\r\n')
                result=s.recv(1024)
                print result
                # Close the socket

        s.close()

print "All hosts completed."

Upvotes: 0

Views: 2342

Answers (1)

lemonhead
lemonhead

Reputation: 5518

Sounds like you just need some basic error handling with a try/except block:

try:
    # run dangerous operation
except TheExceptionThatCouldBeTriggered:
    print("An exception was triggered... continuing")
else:
    # do other stuff if dangerous operation succeeded 

In your case, you want to except socket.error

Upvotes: 1

Related Questions