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
connect_exreports whether a port accepts.- A short timeout keeps closed ports fast.
- Open ports are matched to service names.
Keywords and builtins used here
asdefelseforifis_openlenmainprintreturnsortedwith
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.
Step 1 of 3 in Encore, step 39 of 41 in Domain tools.