Python Ping Script Example
This beginner-friendly example shows how to make a simple Python ping script by running your operating system’s ping command.
This is useful when you want to:
- check whether a host can be reached
- test basic network connectivity
- learn how Python can run terminal commands
- build a small troubleshooting script
Python does not have a simple built-in ping() function for this. A common beginner approach is to run the system command with subprocess.
Quick example #
import platform
import subprocess
host = "google.com"
param = "-n" if platform.system().lower() == "windows" else "-c"
result = subprocess.run(["ping", param, "4", host], capture_output=True, text=True)
print(result.stdout)
print("Reachable" if result.returncode == 0 else "Not reachable")
Note: This uses the operating system ping command. It works as a simple beginner script, but the exact output depends on your system.
What this script does #
This script checks whether a host can be reached over the network.
It does that by:
- choosing the correct
pingoption for your operating system - running the external
pingcommand - collecting the command output
- checking the return code
- printing a simple result message
This is a good example for learning and small utility scripts. It is not a full monitoring system.
When to use a Python ping script #
A script like this is useful when you want to:
- check if a website or device responds
- test network reachability in a simple script
- learn how to run terminal commands from Python
- build small monitoring or troubleshooting tools
If you want more practice with scripts that run checks and report results, see the Python URL checker script example or a Python command-line tool example.
How the example works #
Here is the example again:
import platform
import subprocess
host = "google.com"
param = "-n" if platform.system().lower() == "windows" else "-c"
result = subprocess.run(
["ping", param, "4", host],
capture_output=True,
text=True
)
print(result.stdout)
print("Reachable" if result.returncode == 0 else "Not reachable")
Step by step, the script does this:
- Imports
platformto detect the operating system. - Imports
subprocessto run an external command. - Stores the target host in
host. - Uses
-non Windows and-con macOS/Linux. - Runs
pingwith a count of4. - Saves the result in
result. - Prints the command output.
- Checks
result.returncodeto decide whether the host is reachable.
Key lines to explain #
platform.system().lower() #
platform.system().lower()
This checks the current operating system and turns it into lowercase text.
Examples:
"Windows"becomes"windows""Linux"becomes"linux""Darwin"becomes"darwin"on macOS
That helps the script choose the correct ping option.
subprocess.run(...) #
subprocess.run(["ping", param, "4", host], capture_output=True, text=True)
This runs an external command from Python.
In this case, it runs:
ping -n 4 google.comon Windowsping -c 4 google.comon Linux or macOS
If you are new to running system commands from Python, the os module overview and sys module overview are also useful background topics.
capture_output=True #
capture_output=True
This collects the command output so Python can use it later.
Without this, the command may print directly to the terminal instead of being stored in result.stdout.
text=True #
text=True
This tells Python to return the output as normal text.
Without text=True, the output would be returned as bytes, which is harder for beginners to read.
result.returncode == 0 #
result.returncode == 0
A return code of 0 usually means the command succeeded.
For this script, that usually means the ping command was able to reach the host.
Expected output #
The output will usually show several lines from the ping command, followed by a final message.
Example:
PING google.com (142.250.190.14): 56 data bytes
64 bytes from 142.250.190.14: icmp_seq=0 ttl=117 time=14.2 ms
64 bytes from 142.250.190.14: icmp_seq=1 ttl=117 time=13.8 ms
64 bytes from 142.250.190.14: icmp_seq=2 ttl=117 time=14.0 ms
64 bytes from 142.250.190.14: icmp_seq=3 ttl=117 time=13.9 ms
Reachable
If the host cannot be reached, you may see different output and this final line:
Not reachable
The exact format is different on:
- Windows
- Linux
- macOS
That is normal.
Common beginner problems #
These are the most common reasons a simple ping script does not work as expected:
- using the wrong flag:
-nvs-c - trying to ping a host with no internet connection
- firewall or network rules blocking ping
- the
pingcommand not being available in the current environment - thinking ping success means the whole website or app is working
Common causes #
- Wrong ping flag for the operating system
- Host name is misspelled
- No network connection
- Ping blocked by firewall
- Running in a restricted environment where ping is unavailable
- Assuming return code meanings without checking system behavior
Simple improvements #
Once the basic version works, you can improve it in small steps.
For example, you can:
- let the user enter a hostname
- ping multiple hosts in a loop
- save results to a file
- add a timeout
- show only success or failure instead of the full output
Here is a small improvement that asks the user for a host:
import platform
import subprocess
host = input("Enter a host to ping: ").strip()
param = "-n" if platform.system().lower() == "windows" else "-c"
result = subprocess.run(
["ping", param, "4", host],
capture_output=True,
text=True
)
print(result.stdout)
print("Reachable" if result.returncode == 0 else "Not reachable")
If you want to make this more robust, learn how to handle exceptions in Python. That will help when a command is missing or input is invalid.
Safety and portability notes #
This example is simple on purpose, but a few good habits matter:
- Prefer passing a list to
subprocess.run(...) - Avoid
shell=Truefor simple cases - Remember that command behavior depends on the operating system
- Treat this as a basic example, not a full monitoring solution
Passing a list like this is safer:
["ping", param, "4", host]
That is better than building one shell string yourself.
Debugging commands #
If your script is not working, these commands can help you test the environment:
python ping_script.py
ping google.com
ping -c 4 google.com
ping -n 4 google.com
python --version
Use them like this:
- run
python ping_script.pyto test your script - run
ping google.comdirectly in the terminal to see ifpingworks at all - try
ping -c 4 google.comon Linux or macOS - try
ping -n 4 google.comon Windows - run
python --versionto confirm Python is installed
If Python cannot find a file or command while you test scripts, you may also run into errors like FileNotFoundError: [Errno 2] No such file or directory or PermissionError: [Errno 13] Permission denied.
FAQ #
Does Python have a built-in ping function? #
Not as a simple built-in function. Beginners usually run the system ping command with subprocess.
Why does my script use -n on Windows and -c on Linux or macOS? #
The ping command uses different options on different operating systems.
- Windows uses
-nfor count - Linux and macOS commonly use
-c
Why does the script say Not reachable even when the website opens in my browser? #
Some servers block ping requests. A browser working does not always mean ping will work.
Can I ping an IP address instead of a domain name? #
Yes. You can use:
- a host name like
google.com - an IP address like
8.8.8.8
Is this the best way to monitor servers? #
It is fine for a beginner example.
Real monitoring tools usually need:
- retries
- logging
- timeouts
- better error handling
See also #
- How to make an API request in Python
- Python command-line tool example
- Python URL checker script example
- How to handle exceptions in Python
A good next step is to turn this basic ping script into a small command-line tool that checks user-provided hosts and handles errors clearly.