1

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()
John
  • 11
  • 1
  • Possible duplicate of [python multithreading wait till all threads finished](https://stackoverflow.com/questions/11968689/python-multithreading-wait-till-all-threads-finished) – amitchone May 25 '18 at 11:32

1 Answers1

1

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]
MegaIng
  • 7,361
  • 1
  • 22
  • 35