Ubuntu

Ubuntu – bash script for monitoring CPU, Memory and process

Method-1 : Linux Shell script to monitor CPU utilization with email alert

If you want to get CPU utilization percentage through mail alert when the system reaches the given threshold, use the following script.

This is very simple and straightforward one line script.

It will trigger an email when your system reaches 80% CPU utilization.

*/5 * * * * /usr/bin/cat /proc/loadavg | awk '{print $1}' | awk '{ if($1 > 80) printf("Current CPU Utilization is: %.2f%\n"), $0;}' | mail -s "High CPU Alert" daygeek@gmail.com

Note: Please change the email id and CPU utilization threshold value as per your requirement

Method-2 :Linux Shell script to monitor CPU utilization with email alert

If you want to get more information about the CPU utilization in the mail alert.

Then use the following script, which includes top CPU utilization process details based on the top Command and ps Command.

This will instantly gives you an idea what is going on your system.

It will trigger an email when your system reaches 80% CPU utilization.

Note: Please change the email id and CPU utilization threshold value as per your requirement.

# vi /opt/scripts/cpu-alert.sh

#!/bin/bash
cpuuse=$(cat /proc/loadavg | awk '{print $1}')

if [ "$cpuuse" > 80 ]; then

SUBJECT="ATTENTION: CPU Load Is High on $(hostname) at $(date)"

MESSAGE="/tmp/Mail.out"

TO="daygeek@gmail.com"

  echo "CPU Current Usage is: $cpuuse%" >> $MESSAGE

  echo "" >> $MESSAGE

  echo "+------------------------------------------------------------------+" >> $MESSAGE

  echo "Top CPU Process Using top command" >> $MESSAGE

  echo "+------------------------------------------------------------------+" >> $MESSAGE

  echo "$(top -bn1 | head -20)" >> $MESSAGE

  echo "" >> $MESSAGE

  echo "+------------------------------------------------------------------+" >> $MESSAGE

  echo "Top CPU Process Using ps command" >> $MESSAGE

  echo "+------------------------------------------------------------------+" >> $MESSAGE

  echo "$(ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10)" >> $MESSAGE

  mail -s "$SUBJECT" "$TO" < $MESSAGE

  rm /tmp/Mail.out

  fi

Finally add a cronjob to automate this. It will run for every 5 minutes.

# crontab -e
*/10 * * * * /bin/bash /opt/scripts/cpu-alert.sh

Note: Since the script has scheduled to run once for every 5 minutes  , you will be getting the email alert on 5 minutes interval

Similar Posts