Port scanning can be really slow yet, in most cases, is not process intensive. Thus, we can use threading to improve our speed. There can be thousands of possible ports. If it takes 5-15 seconds per port to scan, then we might have a long wait ahead of us without the use of threading.
Threading
Threading is a complex topic, but it can be broken down and conceptualized as a methodology where we can tell the computer to do another task if the processor is experiencing idle time. In the case of port scanning, we are spending a lot of time just waiting on the response from the server. While we are waiting, we can do something else. That is what threading is used for.
Example: In this program, we can scan a number of ports in a certain range.
Python3
import threading
from queue import Queue
import time
import socket
print_lock = threading.Lock()
target = 'localhost'
def portscan(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try :
con = s.connect((target, port))
with print_lock:
print ( 'port is open' , port)
con.close()
except :
print ( 'port is close' , port)
def threader():
while True :
worker = q.get()
portscan(worker)
q.task_done()
q = Queue()
for x in range ( 4 ):
t = threading.Thread(target = threader)
t.daemon = True
t.start()
start = time.time()
for worker in range ( 1 , 10 ):
q.put(worker)
q.join()
|
Output:
port is close 2
port is close port is close 4
port is closeport is close 1
53
port is close 6port is close
7
port is close 8
port is close 9