0

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."

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm (of course). Thanks for helping out a python-beginner =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.