Shell – Get CPU usage and run a command if it is higher than 80%

cpu usageshell-script

My VPS was hacked several times, hackers put a CPU miner. My hosting provider shutdowns VPS if miner is detected and I did not reactin the next 12 hours. But they can send me notice at 21.00 PM on Saturday 🙂 , and shutdown server at 9.00 AM on Sunday.

So I want to monitor CPU usage and block folder where miner is always revelead from writing.

I'm not very familiar with Linux, so please suggest with such script

  1. Check CPU usage, if it is higher than 80% (as example) Do something.
  2. In my case – delete all from install folder and make it read only.

Actually I've no idea how to implement item â„–1.

Best Answer

I had a similar issue and had this short bash script already done. It is calculating the load average for the last 15 minutes, if you want a different timeframe, it shold be change (to check the load avg for last 5 min, change the awk to print $1).
This will tell you the relative usage of the CPUs :

#!/bin/bash
cores=$(nproc) 
load=$(awk '{print $3}'< /proc/loadavg)
echo | awk -v c="${cores}" -v l="${load}" '{print "relative load is " l*100/c "%"}'

Should run on Ubuntu and Centos.

To get to the point where you check if load is above 80% and 'do something' you should add to this script :

usage=$(echo | awk -v c="${cores}" -v l="${load}" '{print l*100/c}' | awk -F. '{print $1}')
if [[ ${usage} -ge 80 ]]; then
    echo "delete all from install folder and make it read only"
fi
Related Question