Here's the source code for a Fast Host Port Scanner... I added some error handling... but the program is unable to read that error handling thing and it just gives out the normal python error when the host is invalid... Where am I getting it wrong?
How do I print the output of this program to a Text File? (I have tried it at the end but it doesnt work.
Would be Thankful to any help!!
SOURCE CODE:
#!/usr/bin/env python
import socket
import concurrent.futures
import subprocess
import sys
from datetime import datetime
# Clear the screen
subprocess.call('clear', shell=True)
# Ask for input
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
# Prints a banner with info on which host we are about to scan
print ("-" * 60)
print ("Please wait, scanning remote host", remoteServerIP)
print ("-" * 60)
# Check what time the scan started
t1 = datetime.now()
def scan(remoteServerIP, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
try:
remoteServerIP = socket.gethostbyname(remoteServer)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print ("Port {}: Open".format(port))
sock.close()
# We have also put in error handling for catching errors
except KeyboardInterrupt:
print ("You pressed Ctrl+C")
sys.exit()
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print ("Host is not available",)
sys.exit()
with concurrent.futures.ThreadPoolExecutor(max_workers=75) as executor:
for port in range(1,1025):
executor.submit(scan, remoteServerIP, port + 1)
# Checking the time again
t2 = datetime.now()
# Calculates the difference of time, to see how long it took to run the script
total = t2 - t1
# Printing the information to screen
print ('Scanning Completed in: ', total)
#Text file
f = open('Hostreport.txt', 'a')
print(port,file=f)
f.close()
Current OUTPUT Im getting (When etering invalid host):
You are not handling the error! Your error happens on this line. not inside the try except block