I played with my Python port scanner I wrote awhile back.  Rather then just having the script as it was, I wanted to make it more OO.


import socket

# Base class is the scan class. This will be used to initiate the object and set up the expected variables
class Scan(object):
    def __init__(self, host, start_port,end_port):
        self.host = host
        self.start_port = start_port
        self.end_port = end_port

# Machine is a class inhereting from Scan.  When we call it and pass in host,start port, end port - it
# initializes by it's inheritence with Scan.
class Machine(Scan):
    def check_port(self):
        # for loop iterates over a range (defined as the supplied start and end ports)
        for port in range(self.start_port, self.end_port):
            # this is the call to attempt to check the socket on a port
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            connect = sock.connect_ex((self.host, port))
            if connect == 0:
                print("Port " + repr(port) + " : Open")
                    # Now we print out any banners we get when connecting
                except socket.gaierror:
                    print("Hostname could not be resolved")
                except socket.error:
                    # If a time out is reached, we close the session and print a statement
                    print("No Banner Returned")

new_scan = Machine("localhost",0,1090)

Base Class

So we have a base class here called Scan.  The base class initiates the object for variables host, start_port and end_port.

Second Class

A second class is used here called Machine, which inherits from Scan: Machine(Scan).  This way we have a base class that sets up all the init stuff, and we can then pull those values in using the argument “self” in the methods in the Machine class.


The actual scan logic does a for loop.  It loops through a range defined by self.start_port and self.end_port and then connects to each port on that host.

Print Banner Returned

If a connection is established, we print out a message saying the Port is Open and we do a try.  The try clause attempts to grab a banner by doing a print(sock.recv(1024)).  So we’re trying to receive any returned message back out to the console.

If we don’t get a response and time out, we simply close the connection and print out that no banner was available on that open port.

Leave a Reply

Your email address will not be published. Required fields are marked *