typestar

port_scanner.py in Python

Scan a host for open ports from a common list.

"""Scan a host for open TCP ports from a small common list."""
import socket
import sys

COMMON = {22: "ssh", 80: "http", 443: "https", 5432: "postgres",
          6379: "redis", 8080: "http-alt"}


def is_open(host, port, timeout=0.5):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.settimeout(timeout)
        return sock.connect_ex((host, port)) == 0


def main():
    host = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1"
    print(f"scanning {host}")
    found = 0
    for port, name in sorted(COMMON.items()):
        if is_open(host, port):
            print(f"  {port:5d} open   ({name})")
            found += 1
    print(f"{found} of {len(COMMON)} common ports open")


if __name__ == "__main__":
    main()

How it works

  1. connect_ex reports whether a port accepts.
  2. A short timeout keeps closed ports fast.
  3. Open ports are matched to service names.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
668
Tokens
199
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 109 seconds.

Type this snippet

Step 1 of 3 in Encore, step 39 of 41 in Domain tools.

← Previous Next →