Oluwaseun Musa's Blog


Oluwaseun Musa's Blog


How to create a python script to detect open ports on a server

Oluwaseun Musa's photo
Oluwaseun Musa
·Dec 11, 2022·

2 min read

You will first need to import the necessary modules to create a Python script to detect open ports on a server. You can do this using the import statement in Python as follows:

import socket
import os

The socket module provides a low-level interface to the network sockets API, while the os module provides a way to interact with the underlying operating system.

Next, you can create a function that will be used to scan a specific port on the server. This function should take the server's IP address and the port number to be scanned as arguments, and it should return a True value if the port is open or False if the port is closed.

def scan_port(server_ip, port):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((server_ip, port))
        return True
        return False

The scan_port function uses the socket.socket() method to create a new socket object. It then uses the connect() method to attempt to connect to the specified server on the given port. If the connection is successful, the function returns True. If an error occurs, the function returns False instead.

To use this function to scan a range of ports on a server, you can use a for loop to iterate over the range of ports and call the scan_port function for each port in the range. Then, you can print the scan results to the console or save them to a file.

server_ip = ''

for port in range(1, 65535):
    if scan_port(server_ip, port):
        print(f'Port {port} is open')
        print(f'Port {port} is closed')

In this example, the scan_port function is called for each port in the range from 1 to 65535, and the results are printed to the console.

Note that this script will only detect open ports on the local network. To scan ports on a remote server, you will need to use a tool that is designed for this purpose, such as nmap or telnet.

Share this