Python’s Sockets library allows us to make connections to other hosts and we can use this to establish new sockets for our scripts or check if they are open on remote hosts.

With platforms like Octopus for software delivery, we need servers to be able to connect to your company’s Octopus server on certain ports. Also, some software needs to check if a connection can be made to a host on a port. In this class we can check if a port is open on a host and have some logging.

Today we will focus on the class itself and how to setup the hosts. You can take a look at Python’s built in logging function if you’d like as well.

import socket, time, logging
from colorama import init, Fore

# Setup colorama

class PortCheck:
    def __init__(self, domain, port):
        self.domain = domain
        self.port = port
        self.retry = 1
        self.delay = 5
        self.timeout = 3

    def isOpen(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((self.domain, int(self.port)))
            return True
            return False

    def checkHost(self):
        ipup = False
        for i in range(self.retry):
            if self.isOpen():
                ipup = True
        return ipup
    def portReturn(self):
        if self.checkHost():
            print(f"{self.domain}:{self.port} is {Fore.GREEN} OPEN {Fore.RESET}")
  "{self.domain}:{self.port} is OPEN")
            print(f"{Fore.RED}{self.domain}:{self.port} is CLOSED {Fore.RESET}")
            logging.error(f"{self.domain}:{self.port} is CLOSED")

In the class we call checkHost() to connect to the host and port and return if it is open or closed. The portReturn() function we can then have a static and built in way to give us the status of the connection.

To begin we need to create a new instance of the class to check port 443 on

google = PortCheck("", 443)

The variable, google, will now have our class attributes. To make sure we can call google.domain or google.port and this will return and 443 respectfully in this case. To run the work, we call


Once called the class will run the portReturn function that checks our host and connects on the port specified. We should see some thing like the following

Now, lets add a few more hosts.

# Setup hosts and ports
google = PortCheck("", 443)
facebook = PortCheck("", 443)
usefulscriptingnetwork = PortCheck("", 80)
localhost = PortCheck("localhost", 445)
badhost = PortCheck("", 4000)

# run checks

We have now create 5 instances of our PortCheck class each with it’s own information, then running the checks. Once complete we should see something like the following.

I have used colorama to help with a visual on showing the status results in OPEN and CLOSED.

I hope this helps and you can view the full source code on our GitHub Repo.