Skip to content

Instantly share code, notes, and snippets.

@keeth
Created October 10, 2019 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keeth/056ddb7b287f1c469e9564b362ee3564 to your computer and use it in GitHub Desktop.
Save keeth/056ddb7b287f1c469e9564b362ee3564 to your computer and use it in GitHub Desktop.
Monitor packet loss to a particular host and send statistics to Cloudwatch
import threading
import time
import logging
logging.basicConfig(level=logging.INFO, format='[%(levelname)s %(asctime)s %(name)s] %(message)s')
logger = logging.getLogger('pingmon')
logger.setLevel(logging.INFO)
import boto3
from pythonping.executor import Communicator
target = '8.8.4.4'
timeout = 1
client = Communicator(target, None, timeout)
seq = 1
identifier = client.seed_id
attempts = 0
lost = 0
dump_requested = False
session = boto3.Session(profile_name='monitoring')
cloudwatch = session.client('cloudwatch')
def monitor():
global attempts
global lost
while True:
time.sleep(60)
loss = round(100 * lost / attempts)
logger.info('{} packets sent {} packets lost {}% packet loss'.format(attempts, lost, loss))
attempts = 0
lost = 0
cloudwatch.put_metric_data(
MetricData=[
{
'MetricName': 'PacketLoss',
'Unit': 'Percent',
'Value': loss
},
], Namespace='Home')
thread = threading.Thread(target=monitor, args=())
thread.daemon = True
thread.start()
logger.info('pingmon is monitoring {}'.format(target))
while True:
attempts += 1
client.send_ping(client.seed_id, seq, b'a')
res = client.listen_for(identifier, timeout)
if not res.message:
lost += 1
seq = client.increase_seq(seq)
time.sleep(1)
@keeth
Copy link
Author

keeth commented Oct 10, 2019

Ping a host every second. Every minute send packet loss percentage metric to Amazon CloudWatch.

I wrote the script so that I could monitor my upstream internet connection via Raspberry Pi. Sending to Cloudwatch meant that I did not need to log the data to disk and worry about wearing out my SD card.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment