Monitorando processos, CPU e memória

Publicado por eli marques junior (última atualização em 21/08/2013)

[ Hits: 34.898 ]

Download top_of_eli.sh

Download 1377011720.top_of_eli.sh (versão 2)




Simples script para monitorar processos, CPU e memória...
Apenas para brincar e aprender...

A função CPU foi copiada de "by Paul Colby (http://colby.id.au), no rights reserved ;)"

Para executá-lo basta dar permissão:

Ex.:

$ chmod u+x top_of_eli.sh

E executá-lo:

$ ./top_of_eli.sh

  



Versões atualizadas deste script

Versão 2 - Enviado por eli marques junior em 20/08/2013

Changelog: Uso:

$ ./top_of_eli.sh -t "time for sleep" -c "cpu crit" -p "process crit"

Exemplo:

$ ./top_of_eli.sh -t 60 -c 80 -p 10

Download 1377011720.top_of_eli.sh


Esconder código-fonte

#!/bin/bash
# ELI MARQUES JUNIOR
# eli.marquesjunior@gmail.com
#

trap 'echo -e "\n\t\t`tput blink`{FONTE}33[44;1;37mNão é possivel cancelar o script $0{FONTE}33[0m`tput sgr0`\n"; sleep 1; ' 2
process_number=0
function process(){

        quant_proc=0
    FILE="FILE.txt"
    ps -eo pid,%cpu,user,args | grep -v CPU > FILE.txt
    exec 3<&0
    exec 0<$FILE
    # read $FILE using the file descriptors
    while read line
       do

        cpu=`echo $line | awk '{print $2}' | cut -d. -f1`
        process=`echo $line | awk '{print $4}'`

        if (( $cpu >= $1 )); then
                ((quant_proc++))
        echo -e "{FONTE}33[41;1;37m$quant_proc - Process: $process, Uso CPU: $cpu%, Status: CRIT{FONTE}33[0m"

                #output=(0, $quant_proc)
                #echo ${output[@]}
        fi

            #quant_proc=`expr $quant_proc + 1`

    done
    exec 0<&3

        return ${quant_proc[0]}
}


PREV_TOTAL=0
PREV_IDLE=0
function cpu(){
    # by Paul Colby (http://colby.id.au), no rights reserved ;)

        CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
        unset CPU[0]                          # Discard the "cpu" prefix.
        IDLE=${CPU[4]}                        # Get the idle CPU time.

        # Calculate the total CPU time.
        TOTAL=0
        for VALUE in "${CPU[@]}"; do
            let "TOTAL=$TOTAL+$VALUE"
        done

        # Calculate the CPU usage since we last checked.
        let "DIFF_IDLE=$IDLE-$PREV_IDLE"
        let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
        let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
        #echo -en "\rCPU: $DIFF_USAGE%  \b\b"

        # Remember the total and idle CPU times for the next check.
        PREV_TOTAL="$TOTAL"
        PREV_IDLE="$IDLE"

        # Wait before checking again.
}


function memoria(){
    center=$(expr `tput cols` \/ 2 - 25)
    var=(`free -m | grep -i Mem:`)

        var_per=`expr 100 \* ${var[2]} \/ ${var[1]}`
        if (( $var_per >= 88 )); then
             red="{FONTE}33[0m{FONTE}33[41;1;37m"
             nred="{FONTE}33[0m{FONTE}33[46;1;37m"
        else
             red=""
             nred=""
        fi


    printf "%$center.s|----------------------------------------|\n"
    printf "%$center.s|{FONTE}33[44;1;37m             MEMORIA EM MB              {FONTE}33[0m|\n"
    printf "%$center.s|{FONTE}33[44;1;37m------------|-------------|-------------{FONTE}33[0m|\n"
    printf "%$center.s|{FONTE}33[44;1;37m   Total    |    Used     |    Livre    {FONTE}33[0m|\n"
    printf "%$center.s|------------|-------------|-------------|\n"
    printf "%$center.s|{FONTE}33[46;1;37m   %4.4s     |   $red%4.4s$nred      |    %4.4s     {FONTE}33[m|\n" "" "${var[1]}" "${var[2]}" "${var[3]}"
    printf "%$center.s|------------|-------------|-------------|\n"
}


function chama_tudo(){


    while true; do

        printf "%*s\n" $(tput cols) "ELI MARQUES JUNIOR"
        #Chamando a Funcao teste
        memoria

        cpu
            if (($DIFF_USAGE >= 10 )); then
                 printf "Uso CPU: `tput blink`{FONTE}33[41;1;37m%2.2s%%{FONTE}33[0m`tput sgr0`" $DIFF_USAGE
            else
                 printf "Uso CPU: %2.2s%%" $DIFF_USAGE
            fi

        printf "\nProcess Crit:\n"
        #Chamando a Funcao process
        process $1
            #contando=$?

            echo "----------------------------------------------------------------------------------------"

        count=0
        while (($count <= $2)); do

        sleep 1
        ((count++))
                echo -en "\rTime refresh: $count{FONTE}33[179C"

        done
            process_number=$contando
            tput cup 0 0; tput ed
        #printf "{FONTE}33[1K{FONTE}33[H";

    done
}


if [ "-c $2" == "$1 $2" ] && [ "-t $4" == "$3 $4" ]; then
       printf "{FONTE}33[2J{FONTE}33[H";
       chama_tudo $2 $4
else
       echo -e "\t\t\t$0 -c \"arg crit\" -t \"time for sleep\""
fi

Scripts recomendados

Testador de MD5

Script para acionamento de GPIO para Relé Raspberry Pi

Atualização minidns.net

Barra de progresso

Slapt CP 1.0 - salvar os pacotes baixados no Gslapt


  

Comentários
[1] Comentário enviado por mrpawloski em 25/03/2014 - 12:18h

Particularmente prefiro o utilitário "nmon" que faz isso e mais...

É só baixar e executar, já vem pronto.

http://nmon.sourceforge.net/pmwiki.php

This systems administrator, tuner, benchmark tool gives you a huge amount of important performance information in one go. It can output the data in two ways

On screen (console, telnet, VNC, putty or X Windows) using curses for low CPU impact which is updated once every two seconds. You hit single characters on you keyboard to enable/disable the various sorts of data.
You can display the CPU, memory, network, disks (mini graphs or numbers), file systems, NFS, top processes, resources (Linux version & processors) and on Power micro-partition information.
For lots of examples, see the "Screen shots" from the left menu.
As you can see on the left lmon12e now in colour
Save the data to a comma separated file for analysis and longer term data capture.
Use this together with nmon Analyser Excel 2000 spreadsheet, which loads the nmon output file and automatically creates dozens of graphs ready for you to study or write performance reports.
Filter this data, add it to a rrd database (using an excellent freely available utility called rrdtool). This graphs the data to .gif or .png files plus generates the webpage .html file and you can then put the graphs directly on a website automatically on AIX with no need of a Windows based machine.
Directly put the data into a rrd database or other database for your own analysis


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts