Automating Network Monitoring with Bash Scripting: Ping Monitoring and Noti

In today's interconnected world, network reliability is crucial for businesses and individuals alike. Whether you're managing a corporate network or ensuring connectivity in your home environment, being promptly notified of network issues can save valuable time and prevent potential downtime. In this blog post, we'll explore how to automate network monitoring using a simple bash script that pings multiple IP addresses and sends email notifications for both successful and failed pings.

The Script

The bash script we'll be discussing allows us to monitor the availability of multiple IP addresses by periodically pinging them. If a ping is successful, an email notification is sent to a specified email address. Conversely, if a ping fails, another notification is sent. Let's dive into the script.

Bash Code

#!/bin/bash


# Array of IP addresses to ping

IP_ADDRESSES=("192.168.1.1" "192.168.1.2" "192.168.1.3")


# Email address to send notification

EMAIL="your.email@example.com"


# Log file path

LOG_FILE="/opt/script/ping.log"


# Function to send email

send_email() {

 SUBJECT="Ping $1 for $2"

 BODY="Ping to $2 $1."

 echo "$BODY" | mail -s "$SUBJECT" "$EMAIL"

}


# Loop through each IP address

for IP_ADDRESS in "${IP_ADDRESSES[@]}"; do

 # Ping the IP address

 ping -c 4 "$IP_ADDRESS" > /dev/null


 # Check the exit status of ping

 if [ $? -eq 0 ]; then

 echo "Ping successful for $IP_ADDRESS!"

 send_email "successful" "$IP_ADDRESS"

 echo "$(date): Ping successful for $IP_ADDRESS" >> "$LOG_FILE"

 else

 echo "Ping failed for $IP_ADDRESS."

 send_email "failed" "$IP_ADDRESS"

 echo "$(date): Ping failed for $IP_ADDRESS" >> "$LOG_FILE"

 fi

done


How It Works

Setting Up Cron Job

To automate the execution of this script at regular intervals, you can set up a cron job on your system. Simply open the crontab configuration by running crontab -e and add a line to schedule the script execution. For example, to run the script every 5 minutes, you can add the following line:

*/5 * * * * /path/to/ping_script.sh


Replace /path/to/ping_script.sh with the actual path to your script.

Conclusion

With this bash script, you can effortlessly monitor the availability of multiple IP addresses and receive timely notifications via email. Whether you're ensuring the reliability of critical network infrastructure or keeping an eye on home network devices, this automation solution simplifies the process of network monitoring and helps you stay informed about potential issues. Feel free to customize the script according to your specific requirements and integrate additional functionalities as needed.