#!/usr/bin/env python3 import subprocess import sys ############################################################################################ # CONFIGURATION ############################################################################################ HOSTS = { "Cloudflare DNS": "1.1.1.1", "Google DNS": "8.8.8.8", "Quad9 DNS": "9.9.9.9", "Office printer": "192.168.255.254", } IS_WINDOWS = sys.platform == "win32" ############################################################################################ # Functions ############################################################################################ def build_command(host): if IS_WINDOWS: return ["ping", "-n", "1", "-w", "1000", host] return ["ping", "-c", "1", "-w", "1", host] def host_is_reachable(host): """ Returns True if the host answers a single ping. """ # Subprocess can be used to run a command on the host system. # Every argument that you would pass in the shell, becomes an element in the parameter of the subprocess function. # capture_output=True ensures that both stdout and stderr are captured by Python and do not clutter the terminal. # text=True converts the stdout and stderr to text, if set to True, the output is returned as bytes. result = subprocess.run(build_command(host), capture_output=True, text=True) # The returncode property contains the exit code: 0 for a successful reply, 1 for an unreachable host and 2 for a # hostname that doesn't exist. return result.returncode == 0 ############################################################################################ # Main Program ############################################################################################ unreachable = 0 for name, host in HOSTS.items(): if not host_is_reachable(host): print(f"[DOWN] {name:<16} {host}") unreachable += 1 continue print(f"[UP] {name:<16} {host}") print(f"\n{len(HOSTS) - unreachable} of {len(HOSTS)} hosts reachable.") if unreachable > 0: sys.exit(1)