import socket
import sys
import threading
import concurrent.futures
import pyfiglet,time
import colorama
from colorama import Fore
ascii_banner = pyfiglet.figlet_format("Port Scanner")
print(ascii_banner)
print(Fore.GREEN + "Stat time: " + time.asctime())
start = time.perf_counter()
my_file = open("List of OpenPorts.txt", "w")
my_file.write("Port Scanner \n\n")
colorama.init()
print_lock = threading.Lock()
ip = input(Fore.BLUE + "Enter the IP to scan: ")
def scan(ip, port):
scanner = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scanner.settimeout(1)
try:
scanner.connect((ip, port))
scanner.close()
with print_lock:
print(Fore.BLUE + f"Port[{port}]" + Fore.GREEN + " Opened")
my_file.write(f'Port{port} is open \n')
except socket.gaierror:
print("Invalid Hostname. Please enter in a valid hostname")
my_file.write("Invalid Hostname. Please enter in a valid hostname")
with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
for port in range(1025):
executor.submit(scan, ip, port + 1)
finish = time.perf_counter()
print("End time: " +time.asctime())
print(f'Finished in {round(finish - start, 2)} second(s)')
my_file.close()
**Im trying to make the code print only one exception when it encounters a problem. But when the code runs it prints the error code multiple times , I'm guessing it prints it 1025 times because of the threading code . Im not sure how to make it print only one time and end the code afterwards. **
Because every thread is checking for the same error (invalid hostname), if we run
scan()once with a random port number we can check for the invalid hostname before spinning up all 1025 threads.