CPU usage script

Hello Friends,

I am trying to create a shell script which will check the CPU utilization. I use command

top

to check the %CPU usage. It give s me below output

 Cpu states:
CPU   LOAD   USER   NICE    SYS   IDLE  BLOCK  SWAIT   INTR   SSYS
 0    0.31   9.6%   0.0%   6.1%  84.3%   0.0%   0.0%   0.0%   0.0%
 1    0.34  13.0%   0.0%   7.1%  80.0%   0.0%   0.0%   0.0%   0.0%
 2    0.33  13.8%   0.4%   5.5%  80.4%   0.0%   0.0%   0.0%   0.0%
 3    0.33  22.4%   0.0%   5.5%  72.1%   0.0%   0.0%   0.0%   0.0%
 4    0.31  18.5%   0.0%   6.3%  75.2%   0.0%   0.0%   0.0%   0.0%
 5    0.35  16.7%   0.0%   6.9%  76.4%   0.0%   0.0%   0.0%   0.0%
---   ----  -----  -----  -----  -----  -----  -----  -----  -----
avg   0.33  15.6%   0.0%   6.1%  78.3%   0.0%   0.0%   0.0%   0.0%

Below this output it shows several processes and their CPU utilization.
This output changes after 4-5 seconds.

I am trying to develop a script which will add up a value in last row and 6th column ( IDLE) continuously for one minute and take its average. If this average is less than 20 then send a mail to xyz@info.com with body message "CPU utilization is high on server"
for example in one minute values in last row and 6th column changes in one minute as 78,45,67,78,86 then add up all these values and find its average. If it is less than 20 then send mail.
This script should continuously run in background 24*7.

If you are after the server as a whole, then have a look at the manual pages for vmstat and sar as you may be trying to engineer something for which there is already a solution. You also don't want to load processing on to your server to measure how busy it is, because that will just make it busier.

I hope that these help.

Robin
Liverpool/Blackburn
UK

1 Like

Check the load via uptime it gives you the same thing you'd see using top

CPUCHECK=$(uptime | sed the coma out | awk the 10th field
echo $CPUCHECK

Besides the idle column, there are other columns in that top output that also indicate idle time, so you may need to add those as well. Also you need to consider the time span in which the CPU Usage took place. If it is just 5 seconds (checking every 5 seconds may put extra load on your system) then is that bad? Also the time of day may matter..