Building a machine monitoring tool from scratch using Python
A monitoring tool allows users to see the status of a machine at a specific point in time. The status can include 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 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, as 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, followed by used memory. For this, we will utilize the 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.
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 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 of 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.
Not only are IT hires critical to business success, they’re also the most in-demand, making finding the right fit a top priority — and a big challenge. Learn how to efficiently access skilled and diverse talent.
While synchronous collaboration was the preferred method for many global organizations, remote work has increased the popularity of asynchronous communication. But which is more beneficial, both to employees, and to business?