1

I have to do a script in bash to calculate the percentage of CPU and memory usage per session in Linux.

What standard UNIX tools can I use in my script to get this information?

I have this

ML_CPU=$(ps -e -o pcpu= | awk '{sum+=$1} END {print sum}') 

… but I can't get the percentage of CPU for one session, for example for pts/1.

2
  • 3
    Ok. What have you tried? We will not write the script for you but we will be happy to help you solve any specific problems you may have in it.
    – terdon
    Sep 21, 2012 at 1:56
  • I don't want the script, i don't know the command. I have this ML_CPU=$(ps -e -o pcpu= | awk '{sum+=$1} END {print sum}') but i can't get the %cpu for one session. Example for pts/1
    – Freddy
    Sep 21, 2012 at 15:23

1 Answer 1

0

Parsing the output of the following commands should give you what you need:

$ free
$ top -bn 1

Also look into cron, it is a way to run commands at specific intervals. You will probably need to create a crontab for each user that will log the stats for that session.


UPDATE:

I am not sure I understand what you want here. If you need the current CPU % for each pts/tty, try the script below. If you need to collect the total CPU and MEM percentages for a user's session look into cron.

This is a PERL script, if you need BASH let me know.

#!/usr/bin/perl -w
## Collect ps output
open(A, "ps xo pcpu,pmem,tty |");
my %stats;
while (<A>){
    ## Ignore 1st line
    next if $.==1;
    ## Remove new line character (\n)
    chomp;
    ## Get the CPU% and TTY
    /\s*(.+)\s(.+)\s(.+)$/;
    ## Add the CPU% ($1) and MEM% ($2) for each TTY ($3)
    $stats{$3}{CPU}+=$1;
    $stats{$3}{MEM}+=$2;
}
close(A);
## Sort output by CPU%. Use 'sort -nk 5' for MEM%
open(A, "| sort -nk 3");
## The keys of the %stats hash are the different
## TTYs (including '?'). Cycle through and print
foreach (keys(%stats)) {
    print A "$_\tCPU%: $stats{$_}{CPU}  \tMEM%: $stats{$_}{MEM}\n";
}

On my system, I get:

$ ./cpu_percent.pl
pts/0   CPU%: 0     MEM%: 0
pts/2   CPU%: 0     MEM%: 0
pts/3   CPU%: 0     MEM%: 0
pts/4   CPU%: 0     MEM%: 0
pts/5   CPU%: 0     MEM%: 0
pts/7   CPU%: 0     MEM%: 0
pts/8   CPU%: 0     MEM%: 0
tty3    CPU%: 0.3   MEM%: 0
pts/6   CPU%: 0.8   MEM%: 0.5
pts/1   CPU%: 0.9   MEM%: 0.5
?   CPU%: 14.7      MEM%: 15.4

You must log in to answer this question.

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