- Step-1: The Set-up
- Step-2: The Script
- Step-3: Saving The Script
- Step-4: Running The Script
- Explanation of The Script
import socket
import subprocess
import sys
from datetime import datetime
subprocess.call('clear', shell = True)
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
print("-" * 60)
print("Please wait, scanning remote host", remoteServerIP)
print("-" * 60)
t1 = datetime.now()
try:
for port in range(1,5000):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print("Port{}: Open".format(port))
sock.close()
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("Couldn't connect to server")
sys.exit()
t2 = datetime.now()
total = t2 - t1
print("Scanning Completed in", total)
-
Importing Tools (Libraries)
import socketLoads the networking tool. It allows Python to talk to other computers over the internet (create connections, send data, etc.). import subprocessLoads the command line tool. It allows Python to run shell commands (like clearing the screen) just as if you typed them into the terminal yourself. import sysLoads system tools. We mainly use this to exit the program cleanly ( sys.exit()) if an error happens.from datetime import datetimeImports a specific tool to handle time. We need this to check the clock before and after the scan to see how long it took. -
Clearing the Screen
subprocess.call('clear', shell = True)1. What it does: It tells the operating system to run the command clear.
2. Example: Imagine your terminal screen is full of old text. This line wipes it clean so your scanner looks professional.
3. Note:clearworks on Linux and Mac. On Windows, the command iscls. -
Getting User Input & Finding the IP
remoteServer = input("Enter a remote host to scan: ")1. input(...): pauses the program and waits for you to type something.
2. Example: You type google.com. The variable remoteServer now holds the text "https://www.google.com/url?sa=E&source=gmail&q=google.com"remoteServerIP = socket.gethostbyname(remoteServer)1. socket.gethostbyname(...): This is the Phonebook lookup. Computers don't know what "https://www.google.com/url?sa=E&source=gmail&q=google.com" is; they only know IP addresses. This line converts the name into an IP address.
2. Example: It turnsgoogle.cominto142.250.183.46. -
Printing the "Banner"
print("-" * 60)
print("Please wait, scanning remote host", remoteServerIP)
print("-" * 60)1. print("-" * 60): Prints the hyphen character 60 times. It creates a neat horizontal divider line.
2. The result looks like this:
------------------------------------------------------------------
Please wait, scanning remote host (your_remoteServerIP)
------------------------------------------------------------------ -
Starting the Stopwatch
t1 = datetime.now()What it does: It looks at the clock right now and saves that exact time into the variable t1. We will use this later to calculate the total time taken. -
The Main Loop (The Scanner)
try:The safety net. It starts a block of code where we expect errors might happen (like the user pressing Ctrl+C).for port in range(1,5000):1. This creates a loop. The variable portwill start at 1 and go up to 4999 (Python ranges stop before the last number).
2. Analogy: Go to houses numbered 1 through 4999.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)1. What it does: Creates a new socket (a connection endpoint).
2.AF_INET: Says We are using IPv4 (standard IP addresses).
3.SOCK_STREAM: Says We are using TCP (the reliable protocol used for web browsing).
4. Analogy: You are picking up the phone to make a call.sock.settimeout(0.5)What it does: Sets the patience limit to 0.5 seconds. If the server doesn't answer in that time, we give up. result = sock.connect_ex((remoteServerIP, port))sock.connect_ex(...): Tries to connect to the specific IP and Port.
Unlike the normal.connect(), this returns a number instead of crashing if it fails.
Returns0: Success! The port is open.
Returns11(or others): Failure. The port is closed or blocked.if result == 0:Checks if the connection was successful. print(...)If yes, tell the user the port is open. sock.close()Hang up the phone. This is crucial: if you don't close sockets, your computer will run out of resources. -
Handling Errors (The Safety Nets)
except KeyboardInterrupt:print("You pressed Ctrl + C")sys.exit()1. Scenario: You get bored waiting and press Ctrl+Cto stop the script.
2. Action: Python catches that signal, prints a message, and exits cleanly instead of showing a scary error trace.except socket.gaierror:print("Hostname could not be resolved Exiting")<brsys.exit()1. Scenario: You typed a nonsense website name (e.g., sadfjsaldkfjas.com) that doesn't exist in the DNS phonebook.
Action: Prints an error and exits.gaierrorstands for Get Address Info Error.except socket.error:print("Couldn't connect to server")sys.exit()1. Scenario: The server exists, but it's completely down or refusing to talk to you entirely.
2. Action: Prints an error and exits. -
Finishing Up
t2 = datetime.now()Checks the clock again when the loop finishes. total = t2 - t1Calculates the difference (End Time - Start Time). print(...)Shows you exactly how long the scan took (e.g., Scanning Completed in 0:02:15.402).