Python 3 Multi Threaded Port Scanner
nmap does a better job of scanning, fingerprinting, detecting OS, etc. However if you wanted to roll your own port scanner, python can do it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
import socket # as we are opening sockets, need the module import time # time our script import threading # we want to multi thread this from queue import Queue # and have queue management # .45 took 159 seconds (and missed a port) # .25 took 87 seconds # .15 took 54 seconds socket.setdefaulttimeout(0.55) # lock thread during print so we get cleaner outputs print_lock = threading.Lock() # notify user target = input('Host to Scan: ') # convert to ip, if they give us a name # this requires that it actually resolves t_IP = socket.gethostbyname(target) print ('Scanning Host for Open Ports: ', t_IP) # define our port scan process def portscan(port): # create socket object s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # try to connect try: # create/open connection conx = s.connect((t_IP, port)) # don't let thread contention screw up printing with print_lock: print(port, 'is open') # close out that connection conx.close() except: pass # threader thread pulls worker from queue and processes def threader(): while True: # gets worker from queue worker = q.get() # run job with savailable worker in queue (thread) portscan(worker) # complete with the job, shut down thread? q.task_done() # create queue and threader q = Queue() # start time startTime = time.time() # 100 threads took 172 seconds # 200 threads took 87 seconds for x in range(200): # thread id t = threading.Thread(target = threader) # classifying as a daemon, so they will die when the main dies t.daemon = True # begins, must come after daemon definition t.start() # this is the range or variable passed to the worker pool for worker in range(1, 65535): q.put(worker) # wait until thrad terminates q.join() # ok, give us a final time report runtime = float("%0.2f" % (time.time() - startTime)) print("Run Time: ", runtime, "seconds") |
working as a charm!