Types & OOP — The Security Script Foundation

20 min In Progress

Learning Objectives

  • Understand why Python types matter in security contexts
  • Create a class with __init__, attributes, and methods
  • Model a real security concept (Host) as an object

Why Types Matter in Security Scripts

The wrong type breaks your tool silently. An IP address stored as an int behaves completely differently than one stored as a str. Use type() constantly when debugging security scripts.

ip = "192.168.1.1"   # str — always quote IPs
port = 443            # int — numeric
is_open = True        # bool — port state
flags = {"syn": True, "ack": False}  # dict

print(type(ip))       # <class 'str'>
print(type(port))     # <class 'int'>

Your First Security Class — Host

OOP means modelling real things as objects. A Host class holds an IP, its open ports, and methods to interact with it. __init__ runs the moment you create an instance. self refers to that specific object.

class Host:
    def __init__(self, ip):
        self.ip = ip
        self.open_ports = []

    def add_port(self, port):
        self.open_ports.append(port)

    def report(self):
        print(f"Host: {self.ip}")
        print(f"Open ports: {self.open_ports}")

h = Host("192.168.1.10")
h.add_port(22)
h.add_port(80)
h.report()

Dicts as Lookup Tables

In security scripts, dicts are your constant companion — port-to-service mapping, IP-to-hostname, flag-to-value. Memorise dict syntax cold.

services = {
    22:   "SSH",
    80:   "HTTP",
    443:  "HTTPS",
    3389: "RDP",
}

print(services.get(443, "Unknown"))  # HTTPS
print(services.get(9999, "Unknown")) # Unknown

📝 Exercise: Build a Network Asset

Create a NetworkAsset class with ip, hostname, and a list of services. Add two services and print a summary.

code.py
Output

            
← Back to Chapter