i am using the below command in order to find the cpu utilization by a user..now i want to mail if the cpu utilization goes beyond 5%....can someone please help me ?
ps auxw | sort -r +2 | awk '{ print $3,$1 }' | head -6 | egrep "USER|#anonymous#"
%CPU USER
2.0 anonymous
Regards,
Priyank Arora
Yoda
May 20, 2013, 5:55pm
2
You can simplify it a bit:
ps auxw | sort -r +2 | awk 'BEGIN{print "%CPU","USER"}/anonymous/&&$3>5.0{print $3,$1}' > mail_body
[ -s mail_body ] && mail -s "%CPU > 5.0" < mail_body
thanks a lot...
Could you please explain the "> mail_body " section.
i mean do i need to define a variable with the name mail_body ?
or please tell me how to do it if i want to mail it to anonymous@example.com .
Thanks in Advance.
Yoda
May 20, 2013, 7:43pm
4
> mail_body means the output is redirected to a file named: mail_body
In the 2nd step, the if statement is used to check if the file size is greater than zero and send mail if true.
By the way I missed the recipient, it should be:
[ -s mail_body ] && mail -s "Subject" anonymous@example.com < mail_body
you mean
[ -s mail_body ]
checks the size of the file ?
And if i want add a few more lines in the mail then ?
should i create a file mail_body in the beginning of the script and put the content in there ?
for ex. "The Following Process is utilizing High CPU"
Thanks
Yoda
May 20, 2013, 7:58pm
6
Yes. [ -s mail_body ] condition is true when the file size is greater than zero.
For further reference check: Expressions used with if
To add a statement to beginning you can use grouping command form and pipe output to mail:
if [ -s mail_body ]
then
{
echo "Following Processes are utilizing High CPU"
cat mail_body
} | mail -s "Subject" anonymous@example.com
fi
Don't print header-only:
ps aux | sort -r +2 | awk '$2=="anonymous" && $3>5.0 {if (f++==0) print "%CPU","USER"; print $3,$1}' > mail_body
[ -s mail_body ] &&
{
echo "extra text"
cat mail_body
} |
mail -s "%CPU > 5.0" anonymous@example.com