Skip to content

Instantly share code, notes, and snippets.

@ltpitt
Last active April 7, 2022 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ltpitt/a6a3341c809fa26e1dfaba21209a0c75 to your computer and use it in GitHub Desktop.
Save ltpitt/a6a3341c809fa26e1dfaba21209a0c75 to your computer and use it in GitHub Desktop.
Simple snippet to check if a list of hosts has the specified port open or closed
import socket
from contextlib import closing
hosts = ["host1", "host2", "host3"]
port = 22
timeout_in_seconds = 2
hosts_with_opened_port = []
hosts_with_closed_port = []
hosts_with_errors = []
def check_port(host, port, timeout_in_seconds):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout_in_seconds)
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
try:
result = sock.connect_ex((host, port))
if result == 0:
print("Port {} is *** OPEN *** on host: {}".format(port, host))
hosts_with_opened_port.append(host)
else:
print("Port {} is not open on host: {}".format(port, host))
hosts_with_closed_port.append(host)
except socket.gaierror:
print("Port {} check returns a network *** ERROR *** on host: {}".format(port, host))
hosts_with_errors.append(host)
for host in hosts:
check_port(host, port, timeout_in_seconds)
print("\nHosts with opened port:")
print(hosts_with_opened_port)
print("\nHosts with closed port:")
print(hosts_with_closed_port)
print("\nHosts with errors:")
print(hosts_with_errors)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment