Monday, April 21, 2025

Port Scanner in Python - How To

import socket

ip = '192.168.0.103'
port_list = [20, 80, 8080, 139, 445, 23, 21, 22]

for port in port_list:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = s.connect_ex((ip, port))
    if result == 0:
        print('-' * 60)
        print('Port: ', port, 'open')
        print('-' * 60)
    else:
        print('Port: ', port, 'closed')

  1. The first line imports the socket module.
  2. The second line sets the ip variable to '192.168.0.103'.
  3. The third line creates a list of ports to be scanned. The list contains 8 ports: 20, 80, 8080, 139, 445, 23, 21, and 22.
  4. The for loop iterates over each port in the port_list.
  5. For each port in the port_list, the following code is executed: a. A new socket is created using the socket.socket() method with the parameters socket.AF_INET and socket.SOCK_STREAM. b. The connect_ex() method is used to connect to the IP address ip and the current port. c. If the connect_ex() method returns 0, then the port is open and the following is printed:
    • A line of 60 hyphens (-)
    • The port number followed by the word "open"
    • Another line of 60 hyphens d. If the connect_ex() method returns anything other than 0, then the port is closed and the following is printed:
    • The port number followed by the word "closed".

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...