How to Set Up Basic Ping Monitoring with Python: A Step-by-Step Guide

How to Set Up Basic Ping Monitoring with Python: A Step-by-Step Guide

How to Set Up Basic Ping Monitoring with Python: A Step-by-Step Guide

One simple yet effective way to check the status of a network host is by using ICMP ping. I used this script to check if my game servers were available externally and I would get an email if something went wrong.

In this tutorial, we’ll walk through how to create a basic ping monitoring script using Python. This script will not only check the connectivity to a host but also send an email notification if the connection fails.

Prerequisites

Before we dive into the code, make sure you have the following:

  • Python installed on your machine. Python 3.x is recommended.
  • pyping module, which we’ll use to ping a host. You can install it via pip:
pip install pyping
  • smtplib, a Python library for sending emails via SMTP.

The Script

Let’s break down the script into its main components:

  1. Importing Necessary ModulesThe script starts by importing the required libraries:
import pyping
import os
import smtplib
  • pyping is used to send ICMP ping requests.
  • os is included in case you want to extend the script with additional system-related functions.
  • smtplib is used for sending email notifications.

2. Defining the Main Function

The main() function is the core of our script. It handles the ping monitoring and triggers the email notification if the ping fails.

def main():
    mon = pyping.ping('your host')
    if mon.ret_code ==  0:
        print ("Success")
    else:
        sub = "Connection Failed with {}, ping failed".format(mon.ret_code)
        body = "your message baby"
        send_email("sourcemail account","password","[email protected]",sub,body)
  • pyping.ping('your host') sends a ping request to the specified host. Replace 'your host' with the IP address or hostname you want to monitor.
  • If the return code (mon.ret_code) is 0, it means the ping was successful. Otherwise, an email notification is triggered.

3. Sending Email Notifications

The send_email() function handles the process of sending an email if the ping fails:

def send_email(user, pwd, recipient, subject, body):
    import smtplib

    FROM = user
    TO = recipient if isinstance(recipient, list) else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(user, pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print 'successfully sent the mail'
    except:
        print "failed to send mail"
  • The function prepares the email with the given subject and body and sends it using Gmail’s SMTP server.
  • Replace "sourcemail account", "password", and "[email protected]" with your actual email credentials and the recipient’s email address.
  • Ensure that your Gmail account allows “less secure apps” or use an app-specific password if 2FA is enabled.

4. Executing the Script

Finally, the script calls the main() function to start the monitoring process:

main()

How It Works

  1. The script pings the specified host.
  2. If the host is reachable (i.e., the return code is 0), it prints “Success” to the console.
  3. If the host is not reachable, the script formats an email with the subject indicating the failure and sends it to the specified recipient.

Customization

You can customize this script to fit your specific needs:

  • Host to Monitor: Change the 'your host' string to the actual IP address or domain name you want to monitor.
  • Email Notifications: Modify the subject and body of the email to include more detailed information about the failure.
  • Error Handling: Improve the script’s error handling, particularly within the send_email() function, to catch and log specific exceptions.

Conclusion

This basic ping monitoring script is a great starting point for anyone looking to implement simple network monitoring. While it covers the essentials, there’s plenty of room for enhancement, such as logging, alert escalation, or even integrating with a more comprehensive monitoring solution.

With Python’s flexibility, you can easily expand on this script to meet more complex monitoring requirements. Whether you’re managing a small home network or a larger enterprise environment, this tutorial provides the foundation for building your own custom monitoring tools.

Share this content: