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.
1yum 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:
1vi /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 careful it isn’t chopped up by cutting and pasting. The next line of code starts with the echo
.
1#!/bin/sh
2#CGI script for displaying CPU usage on a web page
3
4#Output the header
5echo Content-type: text/html
6echo
7
8#Output the top of the html page
9echo "<html><head><title>CPU Usage</title></head>"
10echo "<body>"
11
12#Stick anything to go above the table on the webpage here
13
14#output the table with the CPU usage
15echo "<table border=1>"
16echo "<tr><td>CPU</td><td colspan=2>% Usage</td></tr>"
17mpstat -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>" }'
18echo "</table>"
19
20#Put anything to go below the table on the webpage here
21
22#Finish off the HTML output.
23echo "</body></html>"
All that’s left to do is make the script executable:
1chmod +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