1

I am trying to measure the cpu usage of my ubuntu machine and if the cpu usage is more than 60%, then I need to find out the process who has the highest cpu usage and then send out an email saying CPU usage is more than 60% and with the process name which has the highest cpu usage.

When I do top this is what I see.

Cpu0  :  20.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Cpu1  :  34.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Cpu2  :  17.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Cpu3  :  20.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st

I came up with the below script which only finds out the cpu load but not the cpu usage. How do I achieve above thing?

#!/bin/bash

top -bn1 | grep load | awk '{printf "CPU Load: %.2f\n", $(NF-2)}' 

To send an email, I use below command and it works for me -

echo "Body" | mailx -r "[email protected]" -s "SUBJECT" "[email protected]"

1 Answer 1

3

using awk:

ps aux --sort=-%cpu | awk 'NR==1{print $2,$3,$11}NR>1{if($3!=0.0) print $2,$3,$11}' > some_file.txt

the above code will give all program with non-zero cpu usage.
will give you pid,%cpu, command_name

if you want cpu usage greater than equal to 60 replace $3!=0.0 to $3>=60

I have saved the output in file some_file.txt. you can cat the file and pipe it to mail command.

try like this: to send mail

cat some_file.txt | mailx -r "[email protected]" -s "SUBJECT" "[email protected]"
3
  • if you wan any modification you can ask me
    – Hackaholic
    Nov 5, 2014 at 22:41
  • thanks a lot hackaholic for the help. How can pipe this thing to my mailx commnad so that it can send out an email if any process has CPU usage greater than 60%?
    – david
    Nov 5, 2014 at 23:22
  • @user2809564 I have edited the code as per your requirement hope that will help.
    – Hackaholic
    Nov 5, 2014 at 23:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .