thread help

Bart Nessux bart_nessux at hotmail.com
Mon Jun 14 15:38:58 EDT 2004


Howdy,

Below is a script that I'm using to try and count the number of HTTP 
servers within a company's private network. There are 65,536 possible 
hosts that may have HTTP servers on them. Any way, I wrote this script 
at first w/o threads. It works, but it takes days to run as it probes 
one IP at a time... so I thought I'd try to make it threaded so it could 
test several dozen IPs at once.

I'm no expert on threading, far from it. Could someone show me how I can 
make this work correctly? I want to probe 64 unique IP address for HTTP 
servers simultaneously, not the same IP addy 64 times (as I'm doing 
now). Any tips would be much appreciated.

Bart

import urllib2, socket, threading, time

class trivialthread(threading.Thread):
    def run(self):
       socket.setdefaulttimeout(1)

       hosts = []
       networks = []

       # Add the network 192.168.0 possibility.
       networks.append("192.168.0.")
       n = 0
       while n < 255:
          n = n + 1
          # Generate and add networks 192.168.1-255 to the list of networks.
          networks.append("192.168.%s." %(n))

       for network in networks:
          h = 0
          # Add the n.n.n.0 host possibility
          hosts.append(network+str(h))
          while h < 255:
             h = h + 1
	    # Add hosts 1 - 255 to each network.
	    hosts.append(network+str(h))

       websites = file('websites.txt', 'w')
       for ip in hosts:
          try:
             f = urllib2.urlopen("http://%s" %ip)
             f.read()
             f.close()
             print>> websites, ip
          except urllib2.URLError:
             print ip
          except socket.timeout:
             print ip, "Timed Out..................."
          except socket.sslerror:
             print ip, "SSL Error..................."
       websites.close()

if __name__ == '__main__':
    threads = []
    for x in range(64):
       thread = trivialthread()
       threads.append(thread)
    for thread in threads:
        thread.start()
    while threading.activeCount() > 0:
        print str(threading.activeCount()), "threads running incl. main"
        time.sleep(1)



More information about the Python-list mailing list