How to Monitor CPU and Memory for High Usage Process on Linux System over Time?


Linux is a very powerful but tricky Operating System. One tiny mistake on configuration can lead to crash or system hung up. In this tutorial, we know how to keep a regular backup without trashing the hard drive. In this post, we know how to ban specific IPs if they cause trouble.

So, if you want to know at real time or in the past (history) that what processes are spiking up CPU usage and/or memory usage, then the following command is right for you. Save the following lines of text using your favourite text editor e.g. vim and then chmod +x the script file.

1
2
3
4
5
#!/bin/bash
#helloacm.com
echo "-------`date`--------"
echo "\t\t%MEM\t%CPU"
ps ax -o comm,%mem,%cpu | sort -nk3 | tail -n 5
#!/bin/bash
#helloacm.com
echo "-------`date`--------"
echo "\t\t%MEM\t%CPU"
ps ax -o comm,%mem,%cpu | sort -nk3 | tail -n 5

These three lines of code will print the top 5 processes that use most CPU and Memory. Example output is like this:

1
2
3
4
5
6
7
-------Thu Nov 13 00:12:44 UTC 2014--------
                %MEM    %CPU
apache2          3.6  7.4
mysqld          13.4  7.7
apache2          4.5 10.3
apache2          3.2 11.7
apache2          4.4 12.2
-------Thu Nov 13 00:12:44 UTC 2014--------
                %MEM    %CPU
apache2          3.6  7.4
mysqld          13.4  7.7
apache2          4.5 10.3
apache2          3.2 11.7
apache2          4.4 12.2

You can then put this in a cronjob that redirects the output to the log file that keeps the history record. Or, if you prefer, you can do a endless loop that monitors in real time and the interval is set to 10 seconds (can be changed). Press Ctrl – C to exit.

1
2
3
4
5
6
7
8
9
10
#!/bin/bash
# helloacm.com
 
while true
do
    echo "-------`date`--------"
    echo "\t\t%MEM\t%CPU"
    ps ax -o comm,%mem,%cpu | sort -nk3 | tail -n 5
    sleep 10
done
#!/bin/bash
# helloacm.com

while true
do
    echo "-------`date`--------"
    echo "\t\t%MEM\t%CPU"
    ps ax -o comm,%mem,%cpu | sort -nk3 | tail -n 5
    sleep 10
done

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
335 words
Last Post: How to Ban Specified IPs in Apache2 Server?
Next Post: Secure the Linux Server by Disallow the Remote Root Login (SSH and FTP and MySQL database)

The Permanent URL is: How to Monitor CPU and Memory for High Usage Process on Linux System over Time?

Leave a Reply