John
John

Reputation: 11

Threading in Python port scanner

I'm trying to write a very simple Port Scanner in Python, and it was working great until I decided to introduce threading, in order to speed things up.

I want to include a brief summary at the end, which lists the ports that are open. I've put this in a function called finish. However, since introducing threading, that summary appears as the first line in the output of my code, no matter where I put it.

Is there a way I can effectively confine threading to the functions I need it for, and then turn it off before it gets to the summary/finish(), or am I just making an obvious mistake? Any help would be much appreciated.

Code:

from socket import *
from threading import *
screenLock = Semaphore(value=1)

open_ports = []

def scan(ip,port):

    try:
        s = socket(AF_INET, SOCK_STREAM)
        s.connect((ip, port))
        screenLock.acquire()
        print ('Scanning ', ip , 'on port',  port)
        print("Port",port, "is open")
        s.close()
        summary(port)

    except:
        screenLock.acquire()
        print ('Scanning ', ip , 'on port',  port)
        print("Port",port,"is closed")

    finally:
        screenLock.release()
        s.close()

def loop():

    for i in range(1,100):
        ip = '192.168.0.38'
        port = int(i)
        t = Thread(target=scan, args=(ip,int(port)))
        t.start()

    return

def summary(port):

    global open_ports
    open_ports.append(port)
    return      

def main():    
    loop()
    finish()

def finish():

    print('The following ports are open:',open_ports) 


main()

Upvotes: 1

Views: 590

Answers (1)

MegaIng
MegaIng

Reputation: 7886

You have to wait for all the Threads to finish:

def loop():
    threads = []
    for i in range(1,100):
        ip = '192.168.0.38'
        port = int(i)
        t = Thread(target=scan, args=(ip,int(port)))
        t.start()
        threads.append(t)
    [t.join() for t in threads]

Upvotes: 1

Related Questions