Shell Script To Check CPU Utilization In Linux Unix
We have already published Shell script to Monitor CPU Utilization and get an email when it is CRITICAL in Usage Check out Article. Here is an One more Shell Script To Check CPU Utilization in Linux Unix Operating systems and store the values in .out file for future reference.
Below is the script which will collect CPU Utilization and store into file and does not apply any validation
#!/bin/bash CPU_USAGE=$(top -b -n2 -p 1 | fgrep "Cpu(s)" | tail -1 | awk -F'id,' -v prefix="$prefix" '{ split($1, vs, ","); v=vs[length(vs)]; sub("%", "", v); printf "%s%.1f%%\n", prefix, 100 - v }') DATE=$(date "+%Y-%m-%d %H:%M:") CPU_USAGE="$DATE CPU: $CPU_USAGE" echo $CPU_USAGE >> /opt/cpu_usage.out
Above Shell Script Output is below
root@ArkIT-Script:/scripts# sh cpuload.sh root@ArkIT-Script:/scripts# cat /opt/cpu_usage.out 2017-07-11 23:08: CPU: 1.2% 2017-07-11 23:22: CPU: 1.5%
But I am not Ok with above script which does not apply any validation the same script i have modified, can validate and send as an email alert when it is CRITICAL
Shell Script To Check CPU Utilization In Linux Unix
#!/bin/bash ## Collect Real Time CPU Usage ## DATE: 12th July 2017 ## Author: Ankam Ravi Kumar CPU_USAGE=$(top -b -n2 -p 1 | fgrep "Cpu(s)" | tail -1 | awk '{ print $8 }' | cut -c1-2) if [ $CPU_USAGE -le 10 ]; then DATE=$(date "+%F %H:%M:%S") CPU_USAGE1="$DATE CPU: $CPU_USAGE" echo "CRITICAL $CPU_USAGE1% Idle" >> /opt/cpusage.out cat /opt/cpusage.out |tail -5 > /tmp/cpusage.tmp mail -s "CPU Utilization of `hostname`" EMAILADDRESS < /tmp/cpusage.tmp elif [ $CPU_USAGE -ge 10 ] && [ $CPU_USAGE -le 20 ]; then DATE=$(date "+%F %H:%M:%S") CPU_USAGE1="$DATE CPU: $CPU_USAGE" echo "WARNING $CPU_USAGE1% Idle" >> /opt/cpusage.out cat /opt/cpusage.out |tail -5 > /tmp/cpusage.tmp mail -s "CPU Utilization of `hostname`" EMAILADDRESS < /tmp/cpusage.tmp else DATE=$(date "+%F %H:%M:%S") CPU_USAGE1="$DATE CPU: $CPU_USAGE" echo "OK $CPU_USAGE1% Idle" >> /opt/cpusage.out fi
Create one file using touch command
# touch 1cpuload.sh
Copy above script and paste in 1cpuload.sh file and run dos2unix filename which will convert from windows format to Unix format to avoid errors while executing shell script
# dos2unix 1cpuload.sh
Note: Before running the CPU Utilization Monitoring Shell script Change EMAILADDRESS
Run the script
root@ArkIT-Script:/scripts# sh 1cpuload.sh root@ArkIT-Script:/scripts# cat /opt/cpusage.out OK 2017-07-11 22:58 CPU: id% Idle OK 2017-07-11 22:59 CPU: 98% Idle OK 2017-07-11 22:59 CPU: 98% Idle OK 2017-07-11 23:31:23 CPU: 98% Idle
That’s it about Monitoring CPU Utilization and storing output values for future reference. If you have any issues with this script please add your comment with error details we will try to help you out.
Related Articles
Delete Blank Lines from file Using AWK tool
What is Shell & Shell Scripting
Learn Linux Step by Step Guide
Thanks for your wonderful Support and Encouragement