Reputation: 23
So I tried to write a port scanner in python3
Here is my code:
import sys #allows us to enter command line arguments, among other things
import socket
from datetime import datetime
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) #Translate a hostname to IPv4
else:
print("Invalid amount of arguments.")
print("Syntax: python3 scanner.py <ip>")
sys.exit()
#Add a banner
print("-" * 50)
print("Scanning target "+target)
print("Time started: "+str(datetime.now()))
print("-" * 50)
try:
for port in range(50,85):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))
if result == 0:
print("Port {} is open".format(port))
s.close()
except KeyboardInterrupt:
print("\nExiting program.")
sys.exit()
except socket.gaierror:
print("Hostname could not be resolved.")
sys.exit()
except socket.error:
print("Couldn't connect to server.")
sys.exit()
using Kali Linux 2020.2, with the newest version of python,
I executes python3 scanner.py google.com
It is expected that the scanner will display "Checking port 50", "Checking port 51" one by one during the scanning process.
And if it find any one of the ports is open, it shows "Port xx is open" after the "Checking port xx"
However, my scanner was stuck as the initial banner.
And eventually when it has completed the scanning, it displays all the output in one go.
Can anyone please tell me how can I solve this problem?
Upvotes: 2
Views: 320
Reputation: 2439
Just switch the following lines in your code:
result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))
becomes:
print("Checking port {}".format(port))
result = s.connect_ex((target,port)) #returns error indicator
Upvotes: 2