ping monitor using python

[Server] ping monitor using python

I need to monitor two way ping/packet loss rate between China and US/Korea/JP for at least 1 day or 2. So here it comes:
pingparsing is a tool to provide ping result summary. It can use under CLI or Python library. Install it using PIP:

pip install pingparsing

sample code for python3:

import json
import pingparsing

ping_parser = pingparsing.PingParsing()
transmitter = pingparsing.PingTransmitter()
transmitter.destination = "google.com"
transmitter.count = 10
result = transmitter.ping()

print(json.dumps(ping_parser.parse(result).as_dict(), indent=4))

result will be:

{
    "rtt_min": 14.741,
    "packet_loss_count": 0,
    "rtt_mdev": 8.019,
    "packet_duplicate_count": 0,
    "packet_duplicate_rate": 0.0,
    "destination": "google.com",
    "rtt_max": 42.696,
    "packet_receive": 10,
    "rtt_avg": 22.206,
    "packet_loss_rate": 0.0,
    "packet_transmit": 10
}

My script to write the result to a txt file:

import pingparsing
import json
import sys
from datetime import datetime

filename = "/tmp/ping_summary_"+str(sys.argv[1])
f2=open(filename,'a')

while (1):
	ping_parser = pingparsing.PingParsing()
	transmitter = pingparsing.PingTransmitter()
	transmitter.destination = str(sys.argv[1])
	transmitter.count = 10
	result = transmitter.ping()
	result_json = ping_parser.parse(result).as_dict()
	f2.write('{0}\t{1}\t{2}\t{3}\t{4}\n'.format(result_json['rtt_min'],result_json['rtt_avg'],result_json['rtt_max'],result_json['packet_loss_rate'],datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
	f2.flush()

Usage of the script:

python3 ping_test 8.8.8.8 &

This script records Min/Avg/Max, packet loss rate and current time to a text file under /tmp. Check back in 1 day and post processing it under excel or something.

Leave a Comment

Leave a Comment

This post is created on April 04, 2020 and last updated on January 22, 2024