M HYPE SPLASH
// news

shell script to monitor cpu usage and alert with top 5 process consuming most CPU

By Abigail Rogers

I need to send an email whenever the CPU utilization goes beyond 70%? How could I do this? When the CPU utilization goes beyond 70%, I also need to get the start commands and process names of the top 5 process, similar to what htop gives

enter image description here

How could I do this with a shell script?

1 Answer

I need to send an email whenever the CPU utilization goes beyond 70%?

I suggest you use an already existing monitoring plugin for this purpose. The plugin check_cpu_stats supports thresholds on CPU usage (not load). There are a couple of different versions of this plugin out there, one example can be found here:

Usage is quite easy:

$ /usr/lib/nagios/plugins/check_cpu_stats.sh -w 70,70,70 -c 80,80,80
CPU STATISTICS OK : user=7.60% system=2.35%, iowait=0.08%, idle=86.94%, nice=3.02%, steal=0.00% | CpuUser=7.60%;70;80;0; CpuSystem=2.35%;70;80;0; CpuIowait=0.08%;70;80;0; CpuIdle=86.94%;0;0;0; CpuNice=3.02%;0;0;0; CpuSteal=0.00%;0;0;0;

Warning thresholds are set to 70% CPU usage on user, system and iowait. Critical thresholds are set to 80% CPU usage on user, system and iowait. You can of course also adapt the thresholds to your environment.

Concerning the alerting part: The best scenario is of course, if you already have this host/machine in an existing monitoring. But you can also use the plugin standalone and send an alert. Example:

/usr/lib/nagios/plugins/check_cpu_stats.sh -w 70,70,70 -c 80,80,80 > /dev/null; if [[ $? -gt 0 ]]; then echo "alert" | mailx -s "cpu alert" ; else echo "no alert"; fi

I also need to get the start commands and process names of the top 5 process

To get the top 5 processes (sorted by cpu usage), you can use the following command (source: ):

ps aux | sort -nrk 3,3 | head -n 5

And now you can combine the monitoring plugin and the process output:

/usr/lib/nagios/plugins/check_cpu_stats.sh -w 70,70,70 -c 80,80,80 > /dev/null; if [[ $? -gt 0 ]]; then echo "$(ps aux | sort -nrk 3,3 | head -n 5)" | mailx -s "cpu alert" ; else echo "no alert"; fi

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy