Network Automation — OOP Port Scanner

25 min In Progress

Learning Objectives

  • Understand how sockets work at the TCP level
  • Use socket.connect_ex() to probe open ports
  • Wrap the scanner in an OOP class with a clean report() method

Sockets — The Foundation

Before Scapy, Nmap, or anything fancy — understand sockets. A socket is a connection endpoint. connect_ex() returns 0 if the port is open, non-zero if closed/filtered. This is how every port scanner works under the hood.

scanme.nmap.org is provided by the Nmap project specifically for legal scanning practice.
import socket

def check_port(host, port, timeout=1):
    """Returns True if port is open."""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        result = s.connect_ex((host, port))
        s.close()
        return result == 0
    except socket.error:
        return False

# scanme.nmap.org is a legal test target
target = "scanme.nmap.org"
for port in [22, 80, 443]:
    status = "OPEN" if check_port(target, port) else "closed"
    print(f"Port {port}: {status}")

OOP Port Scanner — Week 4 Pattern

This is the Week 4 pattern: data in __init__, logic in scan(), output in report(). One class, clean interface, reusable anywhere.

import socket
from datetime import datetime

class PortScanner:
    def __init__(self, target, ports):
        self.target = target
        self.ports = ports
        self.results = {}

    def scan(self):
        print(f"Scanning {self.target} — {datetime.now()}")
        for port in self.ports:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(0.5)
                self.results[port] = s.connect_ex((self.target, port)) == 0
                s.close()
            except socket.error:
                self.results[port] = False

    def report(self):
        for port, is_open in self.results.items():
            status = "OPEN  ✓" if is_open else "closed"
            print(f"  {port:>5}  {status}")

scanner = PortScanner("scanme.nmap.org", [22, 80, 443])
scanner.scan()
scanner.report()

📝 Exercise: Extend the Scanner

Add a method open_ports() to PortScanner that returns a list of only the open port numbers. Then print a summary: 'X of Y ports open'.

code.py
Output

            
← Back to Chapter