Skip to content

Instantly share code, notes, and snippets.

@tonybaloney
Created March 9, 2020 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonybaloney/919070b4901b6ce10a4778fd2081d552 to your computer and use it in GitHub Desktop.
Save tonybaloney/919070b4901b6ce10a4778fd2081d552 to your computer and use it in GitHub Desktop.
Threaded TCP port scanner
from threading import Thread
from queue import Queue
import socket
import time
timeout = 1.0
def check_port(host: str, port: int, results: Queue):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host, port))
if result == 0:
results.put(port)
sock.close()
if __name__ == '__main__':
start = time.time()
host = "something-you-own.com"
scan_range = (80, 100)
threads = []
results = Queue()
for port in range(*scan_range):
# warning - this will create len(scan_range) threads!
t = Thread(target=check_port, args=(host, port, results))
t.start()
threads.append(t)
for t in threads:
t.join()
while not results.empty():
print("Port {0} is open".format(results.get()))
print("Completed scan in {0} seconds".format(time.time() - start))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment