Check Service Ping Status and Exit Code in Python

Ping a list of hosts, print OK/FAIL per host, and exit with a non-zero code when any host is unreachable.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 16 views 0 copies

Python code

30 lines
Python 3.9+
import subprocess
import sys

SERVICES = [
    "8.8.8.8",
    "1.1.1.1",
    "invalid-host",
]

def main():
    failed = []
    for host in SERVICES:
        result = subprocess.run(
            ["ping", "-c", "1", "-W", "2", host],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        status = "OK" if result.returncode == 0 else "FAIL"
        print(f"{host}: {status}")
        if result.returncode != 0:
            failed.append(host)

    if failed:
        print(f"Unreachable hosts: {', '.join(failed)}")
        return 1
    print("All hosts reachable")
    return 0

if __name__ == "__main__":
    sys.exit(main())

Output

stdout
8.8.8.8: OK
1.1.1.1: OK
invalid-host: FAIL
Unreachable hosts: invalid-host

How it works

This script uses subprocess.run to invoke the system ping command with a 2-second timeout per host. Each return code is checked: 0 means reachable, anything else triggers a failure. Failures are collected in a list, and exit code 1 is returned if any host failed. The stdout and stderr are suppressed with DEVNULL so only our formatted messages appear. The return code from main is passed to sys.exit, which the shell sees as the script's exit status.

Common mistakes

  • Omitting `-W` on platforms that don't support it (e.g., Windows uses `-w`).
  • Forgetting `stdout=subprocess.DEVNULL` and seeing raw ping output mixed in.
  • Not using `sys.exit` so the failure exit code is lost.

Variations

  1. Use `socket.gethostbyname` first to validate DNS before pinging.
  2. Replace ping with TCP connection checks for services like HTTP or SSH.

Real-world use cases

  • CI/CD pipeline preflight checks that abort deploys when critical endpoints are down.
  • Network monitoring scripts run via cron to alert when production hosts stop responding.
  • Startup health checks that register services in a load balancer pool only when reachable.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.