Sign up to get Free Ebooks...

I hope you enjoy reading this article. If you are looking for such article ,Click here


Perfect Shell script for monitoring physical memory in Centos and Ubuntu

  • Home
  • /
  • Blog
  • /
  • Perfect Shell script for monitoring physical memory in Centos and Ubuntu
#!/bin/bash
# Set the threshold value for memory usage in percentage
THRESHOLD=80
# Get the total physical memory and free physical memory
if [ -f /etc/redhat-release ]; then
# CentOS
TOTAL_MEM=$(free | awk '/^Mem:/ {print $2}')
FREE_MEM=$(free | awk '/^Mem:/ {print $4}')
elif [ -f /etc/lsb-release ]; then
# Ubuntu
TOTAL_MEM=$(free | awk '/^Mem:/ {print $2}')
FREE_MEM=$(free | awk '/^Mem:/ {print $7}')
else
echo "Unsupported operating system"
exit 1
fi
# Calculate the used memory percentage
USED_MEM=$((100-((FREE_MEM*100)/TOTAL_MEM)))
# Check if the memory usage is above the threshold
if [ $USED_MEM -gt $THRESHOLD ]; then
# If the memory usage is above the threshold, send an email notification
echo "Warning: Memory usage is above threshold of $THRESHOLD%" | mail -s "Memory Usage Alert" user@example.com
fi

In this script, the THRESHOLD variable is set to 80, which represents the percentage of memory usage that should trigger an alert. The script first checks if the operating system is CentOS or Ubuntu by checking the existence of the /etc/redhat-release or /etc/lsb-release file.

The script then uses the free command to get the total physical memory and free physical memory. For CentOS, the awk command is used to extract the values from the second column, while for Ubuntu, the awk command is used to extract the values from the seventh column.

The script then calculates the used memory percentage and checks if it is above the threshold. If it is, the script sends an email notification using the mail command. You can replace user@example.com with the email address you want to receive the notification.

This script can be run as a cron job at regular intervals to continuously monitor the physical memory usage of your CentOS or Ubuntu system and alert you if it exceeds the specified threshold.



November 11, 2024

November 11, 2024

November 11, 2024

June 19, 2023

May 31, 2023

May 9, 2023

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>