SoFunction
Updated on 2024-07-15

How-to Guide for Ping Testing with Python

preamble

In network engineering, Ping test is a commonly used network diagnostic tool to check the reachability and response time of a network connection.Ping test measures the latency and packet loss of a network by sending an ICMP (Internet Control Message Protocol) request packet to a target host and waiting for a response packet to be returned from the target host. With the widespread use of the Python programming language, more and more network engineers are using Python to automate network testing and management tasks. This post will detail how to use Python for Ping testing for beginner network engineers.

Installing Python

First, make sure that Python is installed on your computer. you can check the Python version with the following command:

python --version

If you don't have Python installed, you can get it from the official Python website at/downloadsDownload and install.

There are several libraries in Python that can be used for ping testing, with the ping3 library being an easy-to-use option. The ping3 library can be installed via pip:

pip install ping3

Ensure that your network environment allows ICMP requests to be sent. Some operating systems or network environments may restrict ICMP traffic, which requires appropriate permissions or configuration.

Ping testing with the ping3 library

basic usage

The ping3 library provides a simple function, ping, which can be used to send a ping request and return the response time. The following is a basic example:

from ping3 import ping

response_time = ping('')
print(f'Response time: {response_time} seconds')

In this example, we send a message to theA Ping request is sent and the response time is printed. If the target host is unreachable, the ping function returns None.

Advanced Usage

The ping3 library also provides several other features, such as specifying timeout periods, packet sizes, and so on. Here are some examples of advanced usage:

Specify a timeout period

This can be done bytimeoutparameter specifies the timeout (in seconds) for Ping requests:

response_time = ping('', timeout=2)
print(f'Response time: {response_time} seconds')

Specify packet size

This can be done bysizeparameter specifies the packet size (in bytes) of the Ping request:

response_time = ping('', size=64)
print(f'Response time: {response_time} seconds')

Perform multiple ping tests

Multiple ping tests can be performed using loops to get more data on network performance:

for i in range(5):
    response_time = ping('')
    print(f'Ping {i + 1}: {response_time} seconds')

error handling

In real network environments, ping requests may fail or time out, so error handling is required. ping3 library throws an exception when the target host is unreachable or the request times out, which can be handled using the try-except block:

from ping3 import ping, PingError

try:
    response_time = ping('', timeout=2)
    if response_time is None:
        print('Target is unreachable.')
    else:
        print(f'Response time: {response_time} seconds')
except PingError as e:
    print(f'Ping failed: {e}')

Hands-on: Building a Ping Test Tool

Next, we will build a simple Ping test tool with the following features:

Get the target host from user input and perform multiple ping tests to calculate and display the average response time, maximum response time, minimum response time and packet loss rate.

Realization of tools

1. Obtaining user input

First, code is written to get the target host from user input:

target = input('Enter the target host (., ): ')

2. Perform multiple ping tests

Perform multiple ping tests using a loop and record the response time and number of failures:

from ping3 import ping

num_tests = 10
response_times = []
failures = 0

for i in range(num_tests):
    response_time = ping(target, timeout=2)
    if response_time is None:
        failures += 1
        print(f'Ping {i + 1}: Request timed out.')
    else:
        response_times.append(response_time)
        print(f'Ping {i + 1}: {response_time} seconds')

3. Calculating and displaying statistics

Finally, the average response time, maximum response time, minimum response time and packet loss rate are calculated and displayed:

if response_times:
    avg_response_time = sum(response_times) / len(response_times)
    max_response_time = max(response_times)
    min_response_time = min(response_times)
    packet_loss = (failures / num_tests) * 100

    print(f'\nAverage response time: {avg_response_time:.2f} seconds')
    print(f'Maximum response time: {max_response_time:.2f} seconds')
    print(f'Minimum response time: {min_response_time:.2f} seconds')
    print(f'Packet loss: {packet_loss:.2f}%')
else:
    print('All requests timed out.')

Full Code

Integrate the above steps into a complete Python script:

from ping3 import ping, PingError

def main():
    target = input('Enter the target host (., ): ')
    num_tests = 10
    response_times = []
    failures = 0

    for i in range(num_tests):
        try:
            response_time = ping(target, timeout=2)
            if response_time is None:
                failures += 1
                print(f'Ping {i + 1}: Request timed out.')
            else:
                response_times.append(response_time)
                print(f'Ping {i + 1}: {response_time} seconds')
        except PingError as e:
            failures += 1
            print(f'Ping {i + 1} failed: {e}')

    if response_times:
        avg_response_time = sum(response_times) / len(response_times)
        max_response_time = max(response_times)
        min_response_time = min(response_times)
        packet_loss = (failures / num_tests) * 100

        print(f'\nAverage response time: {avg_response_time:.2f} seconds')
        print(f'Maximum response time: {max_response_time:.2f} seconds')
        print(f'Minimum response time: {min_response_time:.2f} seconds')
        print(f'Packet loss: {packet_loss:.2f}%')
    else:
        print('All requests timed out.')

if __name__ == '__main__':
    main()

Extended functionality

Concurrent Ping Tests Using Multi-Threading

To improve the efficiency of ping tests, concurrent ping tests can be performed using multiple threads.Python's threading module can help with this.

The following is an example of a concurrent ping test using multiple threads:

import threading
from ping3 import ping

def ping_host(target, results, index):
    response_time = ping(target, timeout=2)
    results[index] = response_time

def main():
    target = input('Enter the target host (., ): ')
    num_tests = 10
    threads = []
    results = [None] * num_tests

    for i in range(num_tests):
        thread = (target=ping_host, args=(target, results, i))
        (thread)
        ()

    for thread in threads:
        ()

    response_times = [r for r in results if r is not None]
    failures = (None)

    if response_times:
        avg_response_time = sum(response_times) / len(response_times)
        max_response_time = max(response_times)
        min_response_time = min(response_times)
        packet_loss = (failures / num_tests) * 100

        print(f'\nAverage response time: {avg_response_time:.2f} seconds')
        print(f'Maximum response time: {max_response_time:.2f} seconds')
        print(f'Minimum response time: {min_response_time:.2f} seconds')
        print(f'Packet loss: {packet_loss:.2f}%')
    else:
        print('All requests timed out.')

if __name__ == '__main__':
    main()

Generating Ping Test Reports

Ping test results can be saved to a file to generate a test report for subsequent analysis.

Data can be written to a CSV file using Python's csv module.

The following is an example of generating a Ping test report:

import csv
from ping3 import ping

def main():
    target = input('Enter the target host (., ): ')
    num_tests = 10
    response_times = []
    failures = 0

    with open('ping_report.csv', 'w', newline='') as csvfile:
        fieldnames = ['Ping', 'Response Time']
        writer = (csvfile, fieldnames=fieldnames)
        ()

        for i in range(num_tests):
            response_time = ping(target, timeout=2)
            if response_time is None:
                failures += 1
                print(f'Ping {i + 1}: Request timed out.')
                ({'Ping': i + 1, 'Response Time': 'Request timed out'})
            else:
                response_times.append(response_time)
                print(f'Ping {i + 1}: {response_time} seconds')
                ({'Ping': i + 1, 'Response Time': response_time})

    if response_times:
        avg_response_time = sum(response_times) / len(response_times)
        max_response_time = max(response_times)
        min_response_time = min(response_times)
        packet_loss = (failures / num_tests) * 100

        with open('ping_summary.txt', 'w') as summaryfile:
            (f'Average response time: {avg_response_time:.2f} seconds\n')
            (f'Maximum response time: {max_response_time:.2f} seconds\n')
            (f'Minimum response time: {min_response_time:.2f} seconds\n')
            (f'Packet loss: {packet_loss:.2f}%\n')

        print(f'\nAverage response time: {avg_response_time:.2f} seconds')
        print(f'Maximum response time: {max_response_time:.2f} seconds')
        print(f'Minimum response time: {min_response_time:.2f} seconds')
        print(f'Packet loss: {packet_loss:.2f}%')
    else:
        print('All requests timed out.')

if __name__ == '__main__':
    main()

Post-run response:

Two additional files were generated:

This is the detailed content of the operation guide of Ping test using Python, for more information about Python Ping test, please pay attention to my other related articles!