Machine monitoring tool using python from scratch.
A monitoring tool is a tool that lets us see the status of a machine at a specific point in time. The status we can be looking for includes but is not limited to CPU usage, Network latency, Memory usage, and Disk Usage.
Getting the statistics.
In order to do this, we can use a library for retrieving information from the machine.
psutil (process and system utilities) — a library for retrieving information on -a running processes and system utilization (CPU, memory, disks, network) in python can be a perfect library for this. However, since we want to build the agent from scratch, we will create our own library in order to achieve this.
CPU and System Load
First, we will check the number of both physical and logical CPUs and then check the System Load. For this, we will use the python os
module since it provides methods to access both the number of CPUs and the system load as shown below.
Memory(RAM) usage.
For memory usage, we will start by showing the total memory then show used memory. For this, we will utilize operating system commands sysctl
and vm_stat
to get information about the RAM. We then parse these results and add them to our statistics dictionary as shown below.
Disk Usage.
Here we will get the total disk size, check the used disk space and finally check for the free disk and add all this to the dictionary of statistics.
Network Latency.
Network latency is an expression of how much time it takes for a data packet to get from one designated point to another. Using the Linux ping
command, the round-trip time is considered the network latency. We will use the ping command to determine the network latency of our machine.
All the above have been combined into one file named monitor.py
The output from my machine
Running the Agent
Having been able to collect statistics from above, we need a way to ensure that the script to collect the statistics is executed every 5 minutes(or a custom number of minutes). For this, we will use the Linux crontab to run the monitoring
script.
*/2 * * * * location_to_python3/python3 ~/monitor.py > /tmp/monitor.log 2>&1
Remember to move the monitoring script to the home
directory.
Note:
The above script has only be tested on mac os and little modifications might be needed for it to work on Linux and Windows.