Linux – Best commands to use to find out the total CPU and memory usage of a Linux machine in the following situation

central-processing-unitlinuxmemory

These are pretty much questions from a newbie. (I have looked at the other related questions and answers, but none seemed to be exactly answering my own original questions.)

I need to remotely retrieve, parse, and report in a Java program the CPU and memory usage of a Linux machine. These should be done in two separate commands instead of one to decouple them to make it easier if one command needs to be changed in the future.

So my questions are:

  • What is the best command to use to
    retrieve the total CPU usage of a
    machine for this purpose?
  • What is the best command to use to
    retrieve the total memory usage of
    a machine for this purpose?

By best, I mean the output of the commands are:

  • Standard (independent/should be the same across the Linux flavours — not mandatory, but would be good. target OS though is RHEL 5)
  • Can easily be parsed (not cluttered with other information I am not interested in).

Thanks!

Best Answer

The top command displays both memory and CPU information along with other statistics.

If you want to call it from a script or application use the '-n 1' flag so that it does not run in interactive mode.

e.g to get CPU usage run

 top -n 1 | grep "Cpu"
 (result)
 Cpu(s):  1.6%us,  1.8%sy,  0.0%ni, 92.1%id,  0.6%wa,  0.1%hi,  3.8%si,  0.0%st

for memory usage call

top -n 1 | grep "Mem"
(result)
Mem:   1035240k total,   773088k used,   262152k free,   160348k buffers