Proof-of-Concept Port Scanner

posted in: Python | 0
 
The goal of this project is to create a proof-of-concept port scanner. We will provide an IP address, and it will then perform port scanning on that address.
 
Step 1: Setting Up the Environment
 
We’ll start by creating a new Python file named scanner.py using any text editor of your choice. I will be using the mousepad text editor.
 
 
 
 
i). Then we will name it #!/bin/python3.
 
 
 
Step 2: Importing Modules
 
Import the modules, sys, socket, and datetime for our port scanner.
 
“`
import sys
import socket
from datetime import datetime
“`
 
 
Step 3: Defining the Target
 
1. Define the target IP address for port scanning. 
 
2. Create ‘if’ and ‘else’ statements. – Argv represents the number of arguments. ex. scanner.py (first argument) <ip> (second argument, index of 1 will be the IP address.)
3. We need two arguments so that it doesn’t break. 
 
4. If it does not meet the specified length (len), output ‘Invalid quantity of arguments’ using this “syntax: python3 scanner.py <IP>””
 
5. If it meets the length requirement, we will set our aim equal to socket.gethostbyname(sys.argv[1]).
 
6. sys.argv[1] contains our IP address. – This function converts hostnames to IPv4.
-It is recommended to enter the IP address rather than the hostname, as the latter may not always function.
 
7. This scanner does not have the best logic. This is sufficient for our needs.
 
 
 
“`
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) #Translate hostname to IPv4
 
else:
print(“Invalid amount of arguments.”)
print(“Syntax: python3 scanner.py <ip>”)
“`
 
 
Step 4: Adding a Banner
 
1. Display a banner indicating the target IP address and the start time of the scan.
 
#Add a banner
 
“`
print(“-” * 50)
print(“Scanning target: “+target) #This will say what the <ip> address is.
print(“Time started: “+str(datetime.now())) 
print(“-” * 50)
“` 
 
-Let us try running this and see how it appears.
 
 
 
Step 5: Scanning Ports
 
1. Now, let’s make it do something**.
 
2. We will use the try command, and if it works, great. If not, we will make exceptions.
If it doesn’t, we’ll make exceptions.
 
3. We will use a for loop with a range of 50 to 85 ports:
 
4. We are setting a variable because we are going to gather the IPV4 address (socket.AF_INET) and the port we are attempting to connect to (socket.SOCK_STREAM).
 
`s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)`
 
**–Here is our tuple**
 
5. We shall supply our target. We shall utilize agrv[1]. The port will have the specified range, 50, 85.
 
`result = s.connect_ex((target,port))`
 
6. s.connect_ex is an error indicator. If a port is open, the error result will be 0. If a port is closed, it returns 1.
 
7. if open, print “Port {} is open”.format(port)). If not, call s.close() to close the socket connection on that port and return to the loop. As an example, try 51, 52, 53, etc.
 
8. Because this could be a slow scanner, we’ll set the parameters to somewhere between ports 50 and 85. The reason for this is that we will attempt to scan our home router, which normally has DNS (53), and port 80 open on it.
 
“`
try:
for port in range(50,85):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
 
9. If it fails to respond within one second, we will move on.
 
result = s.connect_ex((target,port)) #returns an error indicator; if a port is open, it throws a 0, otherwise 1
if result == 0:
print(“Port {} is open”.format(port))
s.close()
“`
 
Step 6: Exception Handling
– 
1. What if we get a keyboard interruption? 
 
2. Handle exceptions gracefully, including keyboard interruption, hostname resolution errors, and connection errors.
 
3. In a new line, we shall write, “Exiting program.” Then sys.exit().
 
“`
except KeyboardInterrupt:
print(“\nExiting program.”)
sys.exit()
“`
 
 
2. What happens if the hostname does not resolve? 
 
We will say that the ‘hostname could not be resolved.”
 
“`
except socket.gaierror:
print(“Hostname could not be resolved.”)
sys.exit()
“`
 
2. We will use our default gateway, which should have some ports open.
 
 
– DNS (Port 53) is open.
 
____________________________________________________________________________________________________
 
The whole Python script for this proof-of-concept port scanner is provided below. You can improve on it over time.
 
#!/bin/python3
 
“`
import sys
import socket
from datetime import datetime
 
# Define our target
if len(sys.argv) == 2:
    target = socket.gethostbyname(sys.argv[1])  # Translate hostname to IPv4
else:
    print(“Invalid amount of arguments.”)
    print(“Syntax: python3 scanner.py”)
 
# Add a pretty 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 an error indicator – if port is open it throws a 0, otherwise 1
        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(“Could not connect to server.”)
    sys.exit()
“`

 

 



 
 
3. What if we made a mistake? We’ll say “Could not connect to server.”
 
“`
except socket.error:
print(“Could not connect to server.”)
sys.exit()
“`
 
Step 7: Running the Scanner
 
1. Execute the port scanner script, providing the target IP address to scan. You can observe the output to identify open ports on the target system.
 
2. Let’s run this!
 
To execute this, we’ll need an <ip> address. As we’re scanning our home router, we’ll use our host <ip> address.
 
1. Open CMD as Administrator on your Windows machine.
 
`run ipconfig /all`
 
 
2. We will use our default gateway, which should have some ports open.
 
 
– DNS (Port 53) is open.
 
____________________________________________________________________________________________________
 
The whole Python script for this proof-of-concept port scanner is provided below. You can improve on it over time.
 
#!/bin/python3
 
“`
import sys
import socket
from datetime import datetime
 
# Define our target
if len(sys.argv) == 2:
    target = socket.gethostbyname(sys.argv[1])  # Translate hostname to IPv4
else:
    print(“Invalid amount of arguments.”)
    print(“Syntax: python3 scanner.py”)
 
# Add a pretty 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 an error indicator – if port is open it throws a 0, otherwise 1
        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(“Could not connect to server.”)
    sys.exit()
“`