Python Port Scanner Using Threading
Learn how to build Python Port Scanner Using Threading
Published
Python Port Scanner Using Threading
import socket, threading
from datetime import datetime
try:
#host = "localhost"
host = input("Please Enter host to scan: ")
host_ip = socket.gethostbyname(host)
except socket.gaierror:
print("Host Couldn't be found")
threds = []
open_ports = {}
def check_ports (ip, port, delay, open_ports):
# AF_INET means IP4 address. AF_INET6 means IP6 address
# SOCK_STREAM means we are using TCP. SOCK_DGRAM for UDP
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(delay)
result = sock.connect_ex((ip, port))
if result == 0:
open_ports[port] = 'open'
except socket.gaierror:
print("Host Couldn't be Found")
except socket.error:
print("Socket error happend while connecting server. May host is down.")
def scanning_ports(host_ip, delay, file_reference):
for port in range (1, 1025):
thread = threading.Thread(target=check_ports, args=(host_ip, port, delay, open_ports))
threds.append(thread)
for i in range(0, 1024):
threds[i].start()
for i in range(0, 1024):
threds[i].join()
for key, value in open_ports.items():
print("Open Port Number: " + str(key) )
file_reference.write("\nOpen Port Number: " + str(key))
file_reference = open("port-scanner-4.txt", "w")
start_time = datetime.now()
print("Start Time: {} ".format(start_time))
file_reference.write("Start Time: {} \n".format(start_time))
scanning_ports(host_ip, 0.001, file_reference)
end_time = datetime.now()
print("Start Time: {} ".format(end_time))
file_reference.write("\n\nEnd Time: {} ".format(end_time))
total_time = end_time - start_time
print("Total Time: {} ".format(total_time))
file_reference.write("\nTotal Time: {} ".format(total_time))