Python Port Banner Grabber

As this is considered an Active and not Passive Scan, be sure you either own the hardware you are port scanning, or you have permission to do so.  The legalities depend on geo location, but in some cases have involved arrest, detainment or fines.  Again Рbe sure you have permission (or own the network in question) to perform a port scan.

Banner Grabber

Rather than use a 3rd party tool, a simple script can be written to grab banners as part of a port scan. The script below attempts this as it iterates over a port range. Upon each connection it attempts to grab the banner and then output it.

 

__author__ = 'bwarner'
import socket
socket.setdefaulttimeout(2)
# 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")
            try:
                print(sock.recv(1024))
            except socket.gaierror:
                print("Hostname could not be resolved")
            except socket.error:
                print("No Banner Returned")
            sock.close()

Leave a Reply

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