Results 1 to 9 of 9

Thread: Looking for shell script to Monitor CPU usage and send mail once it exceed 75%

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Rep Power
    0

    Default Looking for shell script to Monitor CPU usage and send mail once it exceed 75%

    Dear Group,

    I'm looking for shell script to monitor cpu usage in background and once it exceeded 75% it should send mail.

    Thanks in advance.

  2. #2
    Senior Member Rahul.Patil's Avatar
    Join Date
    Feb 2012
    Location
    Mumbai india
    Posts
    486
    Thanks
    10
    Thanked 50 Times in 47 Posts
    Rep Power
    8

    Default

    Hi,

    Please check below script


    PHP Code:
    #!/bin/bash
    # Date      = Thu Apr 12 16:52:05 IST 2012
    # author = Rahul Patil
    # Description = Script to check cpu usage and if above threshold issue a linux based command. 
    # This Script only checks "user cpu time (us - userspace (doing userspace stuff)) 
    #
    # Script log file
    LOG="/var/log/cpu.log"

    # Define Threshold
    THRESHOLD=75  ## in percentage

    # wait time(in seconds) after sending mail 
    WAIT=60

    while :
    do
    # Obtain the cpu usage
    thiscpu_usage=$(top --n 1  awk -F'[:,]' '/^Cpu/{sub("\\..*","",$2); print $2}')

    if [ 
    "$thiscpu_usage-ge "$THRESHOLD]; then

    # Send Mail To Systems Admins When CPU usage is above Threshold

    SUBJECT="WARNING CPU USAGE HIGH"

    TO="nobody@emailcompany.com"

    # This is a temp file created for the email message....
    MESSAGE="/tmp/message.txt"

    ps -eo "%cpu,%mem,etime,args" sort -nr -k 1 grep -v CPU head -10 >>  $MESSAGE

    echo "Place the body of your message here" >> $MESSAGE
    echo  "Time: `date`" >> $MESSAGE

    mail 
    -"$SUBJECT" "$TO$MESSAGE

    rm $MESSAGE

    echo "$(tput bold)CPU USAGE   $(tput setaf 1)CRITICLE@@$(date)@@Usage:$thiscpu_usage $(tput sgr 0)" tee -a $LOG

    sleep $WAIT

    else

    echo 
    "$(tput bold)CPU usage is OK @@$(date)@@ $(tput setaf 1)Usage:$thiscpu_usage$(tput sgr 0)" tee -a $LOG
    fi
    done 
    For testing this script use this link or you can simply run below command to generate high cpu usage

    HTML Code:
    while : ; do : ;done
    we can run any script in background using below command

    HTML Code:
    nohup bash /path_of_script_file &
    we can stop script using following command

    HTML Code:
    fuser -k /path_of_script
    also you can check logs

    HTML Code:
    tail -f /var/log/cpu.log

    for configuring mail utility use this link

    reference link
    Last edited by Rahul.Patil; 13th April 2012 at 12:50 AM.

  3. #3
    Senior Member
    Join Date
    Aug 2011
    Posts
    458
    Thanks
    0
    Thanked 62 Times in 58 Posts
    Rep Power
    10

    Default

    hi,

    `grep | awk | awk' is really ugly !
    what's the use of `tail -1'? I don't understand why output two lines to take the last one.
    Code:
    top -b -n 1  | awk -F'[:,]' '/^Cpu/{sub("\\..*","",$2); print $2}'
    HTH
    Last edited by Watael; 12th April 2012 at 10:08 PM.

  4. #4
    Senior Member Rahul.Patil's Avatar
    Join Date
    Feb 2012
    Location
    Mumbai india
    Posts
    486
    Thanks
    10
    Thanked 50 Times in 47 Posts
    Rep Power
    8

    Default

    Hi, Watael
    HTML Code:
    top -b -n 1  | awk -F'[:,]' '/^Cpu/{sub("\\..*","",$2); print $2}'
    thank for giving above trick

    Originally Posted by Watael
    what's the use of `tail -1'? I don't understand why output two lines to take the last one.
    when i use "top -b -n 1" it was giving me same value during testing this script, but now its working fine with your awk trick
    Last edited by Rahul.Patil; 13th April 2012 at 12:43 AM.

  5. #5
    Senior Member
    Join Date
    Aug 2011
    Posts
    458
    Thanks
    0
    Thanked 62 Times in 58 Posts
    Rep Power
    10

    Default

    Code:
    #!/bin/bash
    
    cat <<EOF >~/.toprc
    RCfile for "top with windows"    # shameless braggin'
    Id:a, Mode_altscr=0, Mode_irixps=1, Delay_time=3.000, Curwin=0
    Def   fieldscur=aehioqtwKNMbcdfgjplrsuvyzX
       winflags=42297, sortindx=10, maxtasks=0
       summclr=1, msgsclr=1, headclr=3, taskclr=1
    Job   fieldscur=ABcefgjlrstuvyzMKNHIWOPQDX
       winflags=62777, sortindx=0, maxtasks=0
       summclr=6, msgsclr=6, headclr=7, taskclr=6
    Mem   fieldscur=ANOPQRSTUVbcdefgjlmyzWHIKX
       winflags=62777, sortindx=13, maxtasks=0
       summclr=5, msgsclr=5, headclr=4, taskclr=5
    Usr   fieldscur=ABDECGfhijlopqrstuvyzMKNWX
       winflags=62777, sortindx=4, maxtasks=0
       summclr=3, msgsclr=3, headclr=2, taskclr=3
    EOF
    
    
    trigger=70
    tmpfile=$(mktemp)
    
    #having this script in crontab could be a good idea, instead of using a never ending while loop.
    #while :; do #uncomment to execute for ever
    
    top -b -n1 | awk -v trg="$trigger" 't >= trg && NR > 4 && NR < 15
       NR == 2 {
          t = $0
          sub("[^ ]* *","",t)
          sub("\..*","",t)
          if(t >= trg){print}
       }' > $tmpfile
    
    [ -s "$tmpfile" ] && mail -s "overloadCPU" root@localhost < $tmpfile
    [ -f "$tmpfile" ] && rm "$tmpfile"
    
    #sleep 60 #idem
    #done #idem
    
    rm ~/.toprc
    I didn't write the .toprc file myself, I only recorded from `top', and copy/paste it in the script.
    Last edited by Watael; 13th April 2012 at 04:21 AM.

  6. #6
    Junior Member
    Join Date
    Apr 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Rep Power
    0

    Default

    Hi Rahul,

    First thanks for your replay.
    in your script what I understood after ran the script that I should wait till the THRESHOLD reached 75 but what I'm looking for is once the CPU&#37; reached 75% email should be trigger, and I would like to know how to make this script run in the cron job continually.

  7. #7
    Senior Member Rahul.Patil's Avatar
    Join Date
    Feb 2012
    Location
    Mumbai india
    Posts
    486
    Thanks
    10
    Thanked 50 Times in 47 Posts
    Rep Power
    8

    Default

    Hi clfever,
    you can run this script using cron but for that you need to comment while loop.
    for cron, add following entry in "/etc/crontab" then once restart cron service
    #Ex.
    # run every 5 minut
    */5 * * * * root /absolute_path_of_script_file

    for more information about cron use this link

  8. #8
    Junior Member
    Join Date
    Nov 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Rep Power
    0

    Default

    try using

    memUsage=`sar -q 1 | tail -1 | awk '{ print "" $3}' | sed 's/%//g'`

    this doesnt give the memory usage in percentage terms but if it could be of use.

    Thanks & Regards,
    vivek

    Quote Originally Posted by clfever View Post
    Dear Group,

    I'm looking for shell script to monitor cpu usage in background and once it exceeded 75&#37; it should send mail.

    Thanks in advance.

  9. #9
    Junior Member
    Join Date
    Mar 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Rep Power
    0

    Default

    Quote Originally Posted by Rahul.Patil View Post
    Hi,
    Please check below script
    Thanks for your script, based onto your script I wrote own tuned for muliple CPUs and tuned 'top' command for OS FreeBSD.
    by this link at my profile present my publication with description.

    Code:
    #!/usr/local/bin/bash
    #monitoring idle state per processor core
    # Script log file
    LOG="/var/log/cpu.log"
    
    
    # Define Threshold
    THRESHOLD=5  ## in percentage idle
    
    
    TO="postmaster@example.com"
    MESSAGE="/tmp/monitor-cpu-message.txt"
    
    
    # wait time(in seconds) after sending mail
    WAITMAIL=300
    # wait time(in seconds) after loop
    WAIT=8
    # wait time (in seconds) in critical zone
    INITWINDOW=120
    
    
    #fill init value for all CPUs
    for index in 0 1 2 3
    do
     WINDOW[index]=$INITWINDOW
    done
    
    
    function checkwindow() {
        if [ $1 -eq 0 ]; then
            IDLE=$3
            let "usage=100-IDLE"
            SUBJECT="WARNING CPU$2 USAGE HIGH"
            ps -o "%cpu,args" | sort -nr -k 1  | head -10 &gt;&gt;  $MESSAGE
            echo "." &gt;&gt; $MESSAGE
            echo "Usage of CPU$2 is $usage% during $INITWINDOW sec." &gt;&gt; $MESSAGE
            echo  "Time: `date`" &gt;&gt; $MESSAGE
            mail -s "$SUBJECT" "$TO" &lt; $MESSAGE
            rm $MESSAGE
            echo "CPU$2 USAGE CRITICLE @@$(date)@@ Usage:$usage" | tee -a $LOG
            sleep $WAITMAIL
        fi
    }
    
    
    while :
    do
    CPU=0
      for thiscpu_usage in $(top -b -d 2 -I -P  | awk '/^CPU/{sub(/\.+% idle$/,"");  print int($11)}') ; do
        if [ "$thiscpu_usage" -le "$THRESHOLD" ]; then
            let "WINDOW[CPU]=WINDOW[CPU]-2-WAIT"
        #    echo "CPU$CPU $thiscpu_usage ${WINDOW[$CPU]}"
            checkwindow ${WINDOW[$CPU]} $CPU $thiscpu_usage
        else
            WINDOW[$CPU]=$INITWINDOW
        #    echo "CPU$CPU usage is OK @@$(date)@@ Idle:$thiscpu_usage%" | tee -a $LOG
        fi
      let "CPU=CPU+1"
      done
    sleep $WAIT
    done

Thread Information

Users Browsing this Thread

There are currently 2 users browsing this thread. (0 members and 2 guests)

Similar Threads

  1. Send mail using shell script
    By suvajit_sid in forum Shell scripting
    Replies: 2
    Last Post: 23rd June 2011, 11:58 PM
  2. Shell script to convert output to html then send mail
    By palsec in forum Shell scripting
    Replies: 7
    Last Post: 8th December 2010, 06:07 PM
  3. Replies: 1
    Last Post: 25th September 2009, 11:59 AM
  4. Replies: 1
    Last Post: 11th February 2008, 02:01 PM
  5. shell script to send mail for each login.
    By ephdia in forum Shell scripting
    Replies: 2
    Last Post: 27th November 2007, 04:42 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •