Skip to content

Latest commit

 

History

26 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

Python Network Port Scanner

Content

Step-1: The Set-up

1. Open Any Linux Terminal View
2. cat > portscan.py View
3. Enter View
4. Ctrl + C View
5. ls View Here, you should see portscan.py(file) not same color as other directories(blue)
6. nano portscan.py View
7. Enter View
8. Copy & Paste:
Copy Ctrl + C for windows
Below Step-2: The script
Paste Ctrl + Shift + V for Linux
in your terminal file(portscan.py)
View in your linux terminal
Zoom out: Ctrl + -
Zoom in: Ctrl + Shift + +

Step-2: 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)

Step-3: Saving The Script

9. Exiting from the script File.
Ctrl + X
View
10. Saving script File Before Exiting.
Y Yes
View
11. Want to Rename( nano portscan.py )
or name( if not given nano only ).
View If already name it will ask keep it portscan.py or change it.
If not named( nano only ) it will ask for to give a name to your script file.
12. Enter View

Step-4: Running The Script

13. python portscan.py View You are telling your computer,
"Use the Python program to read and run
the instructions inside the file portscan.py".
14. Enter View
15. Enter a remote host to scan: scanme.nmap.org View # target that we want to scan for open ports if any
Nmap project provides a specific authorized target
16. Enter View you can see scanme.nmap.org provided as with target IP address.
wait for few minutes
17. found my first open port View wait few more minutes for script to end
18. script Ended View After waiting for 41 minutes Project Done !!

Explanation of The Script

  • Importing Tools (Libraries)

    import socket Loads the networking tool. It allows Python to talk to other computers over the internet (create connections, send data, etc.).
    import subprocess Loads 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 sys Loads system tools. We mainly use this to exit the program cleanly ( sys.exit() ) if an error happens.
    from datetime import datetime Imports 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: clear works on Linux and Mac. On Windows, the command is cls.
  • 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 turns google.com into 142.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 port will 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.
    Returns 0 : Success! The port is open.
    Returns 11 (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 + C to 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")<br sys.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. gaierror stands 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 - t1 Calculates the difference (End Time - Start Time).
    print(...) Shows you exactly how long the scan took (e.g., Scanning Completed in 0:02:15.402 ).

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors