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.
Python code
30 linesimport 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
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
- Use `socket.gethostbyname` first to validate DNS before pinging.
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.