import socket, select ports = [22,80,33,100,139,200,345,234,465,132] sockets = [] for port in ports: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # sock.setblocking(False) # sock.settimeout(3) # Start connection attempt (does NOT wait for it to finish, # so we have no idea if it is going to be successful yet. print sockets try: sock.connect_ex(('localhost', port)) except socket.error: pass sockets.append(sock) while sockets: # We're only waiting for sockets to become writeable. # that's when we know if the connect succeeded. rdable, wrtable, weird = select.select([], sockets, []) for sock in wrtable: # Hmm, the OS says a write() on the socket won't block. # This means we either connected successfully, or there's a socket # error pending (i.e. connection refused) that will cause a write() # to return immediately. Let's just try. try: sock.write("I'm a portscan!\n") print "Hmm, it seems I was able to connect to host port " except: print "Failed to connect to host port " # Okay, we're done, we're now no longer interested in this socket. sock.close() sockets.remove(sock) # Done with processing, loop into the select again and wait for the next # socket to become interesting.