Python Port Scanner (project-1)
Learn how to build Python Port Scanner
Published
import socket
import sys
from datetime import datetime
file = open("Port-Scanner.txt", "w")
try:
host = input("Please Enter host to Scan: ")
#host = "localhost"
host_ip = socket.gethostbyname(host)
file.write("\nScanning Host: {}\n".format(host_ip))
t1 = datetime.now()
print("Start Time: {}".format(t1))
file.write("Start Time: {}\n".format(t1))
print("Finding Open Ports: In-Progress......")
for port in range(1, 1025):
# AF_INET means IP4 address. AF_INET6 means IP6 address
# SOCK_STREAM means we are using TCP. SOCK_DGRAM for UDP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.001)
result = sock.connect_ex((host_ip, port))
if result == 0:
print("Port {} is Open".format(port))
file.write("\nPort {} is Open".format(port))
except socket.gaierror:
print("HostName you Entered is not correct")
file.write("\nHostName you Entered is not correct")
sys.exit()
except socket.error:
print("Couldn't connect to Server")
file.write("\nCouldn't connect to Server")
sys.exit()
t2 = datetime.now()
print("End Time: {}".format(t2))
file.write("\n\nEnd Time: {}".format(t2))
total_time = t2 - t1
print("Total Time: {}".format(total_time))
file.write("\n\nTotal Time: {}".format(total_time))