Webpage to Monitor CPU usage on a linux box.

This cgi script allows you to post a webpage on your multi-processor Linux server which shows the current CPU usage. Useful if you want to quickly and easily check the load on the system and see if multi-processor applications are spreading themselves across the available cores.

This code has been tested on a 48-core server running Centos 5. The usual disclaimers apply.

Prerequisites

For this script to work you will need a Linux system with a cgi-capable webserver installed and running. My system has apache on it, but whatever flavour you like is probably fine. The server will also need the “sh” shell installed and the “mpstat” command. The latter is part of the “sysstat” package so can be installed on Centos/Fedora/RedHat systems with the command.

yum install sysstat

Installation

Using your favourite editor open a new text file called “cpu.cgi” in the cgi-bin folder on your server, for example:

vi /var/www/cgi-bin/cpu.cgi

And copy and paste in the following code. Be aware the line starting “mpstat” is quite long so be carful it isn’t chopped up by cutting and pasting. The next line of code starts with the “echo”.

 
#!/bin/sh
#CGI script for displaying CPU usage on a web page

#Output the header
echo Content-type: text/html
echo

#Output the top of the html page
echo "<html><head><title>CPU Usage</title></head>"
echo "<body>"

#Stick anything to go above the table on the webpage here

#output the table with the CPU usage
echo "<table border=1>"
echo "<tr><td>CPU</td><td colspan=2>% Usage</td></tr>"
mpstat -P ALL 1 1 | sed /^$/d | sed /^Linux/d | sed -n '/CPU/,/CPU/p' | sed /CPU/d | awk ' { print "<tr><td>",$2,"</td><td>",100-$10,"</td><td><div style="width:",(100-$10)*2,"px;background:green;border: 1px solid black;"> </div></td></tr>" }'
echo "</table>"

#Put anything to go below the table on the webpage here

#Finish off the HTML output.
echo "</body></html>"

All that’s left to do is make the script executable:

chmod +x /var/www/cgi-bin/cpu.cgi

And now just point your web browser at the following URL to view the results.
http://myserver/cgi-bin/cpu.cgi

Leave a Reply

Your email address will not be published. Required fields are marked *