Sobes.tech
Junior

How to check the availability of a port on a remote machine?

sobes.tech AI

Answer from AI

You can use the socket module.

import socket

def is_port_open(host, port, timeout=1):
    """
    Checks the availability of a port on a remote machine.

    Args:
        host (str): IP address or hostname.
        port (int): Port number.
        timeout (int): Connection timeout in seconds.

    Returns:
        bool: True if the port is open, False otherwise.
    """
    try:
        s = socket.create_connection((host, port), timeout)
        s.close()
        return True
    except (socket.timeout, ConnectionRefusedError, OSError):
        return False

# Example usage
if is_port_open("example.com", 80):
    print("Port 80 on example.com is open.")
else:
    print("Port 80 on example.com is closed.")

You can also use higher-level libraries, such as paramiko for SSH, if you need to check the availability of SSH services.

import paramiko

def cab_ssh_connect(hostname: str, port: int, timeout: int) -> bool:
    """
    Checks the possibility of SSH connection.

    Args:
        hostname (str): Hostname or IP address.
        port (int): SSH port.
        timeout (int): Connection timeout in seconds.

    Returns:
        bool: True if connection is possible, otherwise False.
    """
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(hostname, port=port, timeout=timeout)
        return True
    except (paramiko.AuthenticationException, paramiko.SSHException, socket.error, TimeoutError):
        return False
    finally:
        client.close()

# Example usage
if cab_ssh_connect("example.com", 22, 5):
    print("SSH port 22 on example.com is open.")
else:
    print("SSH port 22 on example.com is closed or timeout.")

The choice of method depends on the specific task and protocol used by the port. The most universal way is to use socket.