HOWTO · Python
How to Ping A Server using Python
This tutorial demonstrates how to ping a server in Python
On this page
To check whether a host responds to ICMP echo requests from Python, call the operating system’s ping command with subprocess.call() or os.system(), or use the ping3.ping() function. A response can show host reachability and provide round-trip time, but it does not prove that a particular application or service is available. Results also depend on the operating system, installed tools, firewall rules, and network policy.
Ping a Server in Python with subprocess.call()
subprocess.call() runs a program and returns its process exit status. Passing the command as a list avoids building a shell command from the host string. The packet-count option differs by platform: common ping implementations use -n on Windows and -c on Unix-like systems.
import platform
import shutil
import subprocess
def ping_host(host):
ping = shutil.which("ping")
if ping is None:
return None # The ping program is not installed or on PATH.
count_option = "-n" if platform.system() == "Windows" else "-c"
try:
status = subprocess.call(
[ping, count_option, "1", host],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5,
)
except (OSError, subprocess.TimeoutExpired):
return None
return status == 0
result = ping_host("example.com")
if result is None:
print("ping is unavailable")
else:
print("host responded" if result else "no successful response")
Observed output in the supplied run environment:
ping is unavailable
The supplied run environment did not have ping available, as the output shows. In an environment where it is installed, this example also requires network access. It suppresses command output and returns True when the process exits with status zero, False for a nonzero status, or None when the program is unavailable or times out. A nonzero status does not identify whether the cause was packet loss, filtering, name resolution, or another system-specific condition. Change the host and packet-count option to suit your environment.
Ping a Server in Python with os.system()
os.system() runs a command string through a shell and returns a status encoded by the platform. This is less flexible than subprocess.call(), and concatenating untrusted host text into a command can allow shell injection. Prefer an argument list with subprocess.call() for values that may come from users. If using os.system() with a fixed, trusted host, select the packet-count option for the current platform:
import os
import platform
import shutil
host = "example.com" # Keep this fixed or validate it before use.
ping = shutil.which("ping")
if ping is None:
print("ping is unavailable")
else:
count_option = "-n" if platform.system() == "Windows" else "-c"
status = os.system(f'"{ping}" {count_option} 1 {host} > "{os.devnull}" 2>&1')
print("host responded" if status == 0 else "no successful response")
Observed output in the supplied run environment:
ping is unavailable
The supplied run environment did not have ping available, as the output shows. When it is available, this example depends on the local shell, ping implementation, and network. Quoting the executable path handles spaces in that path, but shell command strings still need careful treatment; do not substitute arbitrary user input for host. The status indicates the shell command’s result, not whether a service such as a web server is accepting connections.
Ping a Server in Python with ping3.ping()
The third option is the ping3.ping() function, which sends an ICMP echo request without invoking the system ping command. Install the ping3 package in the Python environment used by your script with python -m pip install ping3. Depending on the operating system and privileges, sending ICMP packets may require additional permissions.
try:
from ping3 import ping
except ImportError:
print("Install ping3 with: python -m pip install ping3")
else:
host = "example.com"
response = ping(host)
if response is None or response is False:
print("no response reported")
else:
print(f"round-trip time: {response} seconds")
Observed output in the supplied run environment:
Install ping3 with: python -m pip install ping3
The supplied run environment did not have ping3 installed, as the output shows. After installing it, the example also requires suitable ICMP permissions and network access. A numeric response represents round-trip time in seconds. Interpret a lack of response according to the installed library’s behavior and environment; do not assume it distinguishes an unreachable host from filtered or lost packets.
Choose subprocess.call() when you want to pass arguments safely and use the system’s established ping utility. os.system() is a shorter shell-based option for a fixed, trusted command. ping3.ping() keeps the call in Python and can return timing information, but adds a package and permission considerations. In all three cases, ping tests ICMP reachability only; use an application-level check when you need to know whether a specific service is working.