System Monitoring Made Easy with Python’s Psutil Library
System Monitoring using Python
In today’s world, where we heavily depend on computers and servers to carry out various tasks, it’s essential to monitor our systems’ performance regularly. Monitoring system performance helps detect potential issues and optimize the system for better performance. In this article, we will explore how to monitor system performance using Python’s psutil library.
Python’s psutil library is a cross-platform library for retrieving information about system utilization, processes, and system resources such as CPU, memory, disks, and network. It’s a powerful tool that provides easy access to system-level information with just a few lines of Python code.
systems_monitoring.py
import os
import psutil
import json
import subprocess
import time
def get_kernel_info():
return {
"kernel_version": os.uname().release,
"system_name": os.uname().sysname,
"node_name": os.uname().nodename,
"machine": os.uname().machine
}
def get_memory_info():
return {
"total_memory": psutil.virtual_memory().total / (1024.0 ** 3),
"available_memory": psutil.virtual_memory().available / (1024.0 ** 3),
"used_memory": psutil.virtual_memory().used / (1024.0 ** 3),
"memory_percentage": psutil.virtual_memory().percent
}
def get_cpu_info():
return {
"physical_cores": psutil.cpu_count(logical=False),
"total_cores": psutil.cpu_count(logical=True),
"processor_speed": psutil.cpu_freq().current,
"cpu_usage_per_core": dict(enumerate(psutil.cpu_percent(percpu=True, interval=1))),
"total_cpu_usage": psutil.cpu_percent(interval=1)
}
def get_disk_info():
partitions = psutil.disk_partitions()
disk_info = {}
for partition in partitions:
partition_usage = psutil.disk_usage(partition.mountpoint)
disk_info[partition.mountpoint] = {
"total_space": partition_usage.total / (1024.0 ** 3),
"used_space": partition_usage.used / (1024.0 ** 3),
"free_space": partition_usage.free / (1024.0 ** 3),
"usage_percentage": partition_usage.percent
}
return disk_info
def get_network_info():
net_io_counters = psutil.net_io_counters()
return {
"bytes_sent": net_io_counters.bytes_sent,
"bytes_recv": net_io_counters.bytes_recv
}
def get_process_info():
process_info = []
for process in psutil.process_iter(['pid', 'name', 'memory_percent', 'cpu_percent']):
try:
process_info.append({
"pid": process.info['pid'],
"name": process.info['name'],
"memory_percent": process.info['memory_percent'],
"cpu_percent": process.info['cpu_percent']
})
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return process_info
def get_load_average():
load_avg_1, load_avg_5, load_avg_15 = psutil.getloadavg()
return {
"load_average_1": load_avg_1,
"load_average_5": load_avg_5,
"load_average_15": load_avg_15
}
def get_disk_io_counters():
io_counters = psutil.disk_io_counters()
return {
"read_count": io_counters.read_count,
"write_count": io_counters.write_count,
"read_bytes": io_counters.read_bytes,
"write_bytes": io_counters.write_bytes,
"read_time": io_counters.read_time,
"write_time": io_counters.write_time
}
def get_net_io_counters():
io_counters = psutil.net_io_counters()
return {
"bytes_sent": io_counters.bytes_sent,
"bytes_recv": io_counters.bytes_recv,
"packets_sent": io_counters.packets_sent,
"packets_recv": io_counters.packets_recv,
"errin": io_counters.errin,
"errout": io_counters.errout,
"dropin": io_counters.dropin,
"dropout": io_counters.dropout
}
def get_system_uptime():
boot_time_timestamp = psutil.boot_time()
current_time_timestamp = time.time()
uptime_seconds = current_time_timestamp - boot_time_timestamp
uptime_minutes = uptime_seconds // 60
uptime_hours = uptime_minutes // 60
uptime_days = uptime_hours // 24
uptime_str = f"{int(uptime_days)} days, {int(uptime_hours % 24)} hours, {int(uptime_minutes % 60)} minutes, {int(uptime_seconds % 60)} seconds"
return {"uptime": uptime_str}
if __name__ == '__main__':
data = {
"kernel_info": get_kernel_info(),
"memory_info": get_memory_info(),
"cpu_info": get_cpu_info(),
"disk_info": get_disk_info(),
"network_info": get_network_info(),
"process_info": get_process_info(),
"system_uptime": get_system_uptime(),
"load_average": get_load_average(),
"disk_io_counters": get_disk_io_counters(),
"net_io_counters": get_net_io_counters(),
}
print("="*40)
print("System Monitoring")
print("="*40)
print(json.dumps(data, indent=4))
requirements.txt
psutil==5.9.4
In the code above, we have defined various functions that retrieve different types of system information such as kernel version, memory usage, CPU usage, disk usage, network usage, process information, system uptime, load average, disk I/O counters, and network I/O counters.
To retrieve the system information, we call these functions and store the output in a dictionary called data. The final output is a formatted JSON string that displays all the system information in a readable format.
One of the benefits of using Python’s psutil library is that it provides cross-platform compatibility, meaning that it works on multiple operating systems, including Windows, Linux, and macOS. It’s a lightweight library that does not consume many system resources, and it’s easy to install using pip, the Python package manager.
Another benefit of using Python’s psutil library is that it provides a lot of information about the system, which we can use to diagnose performance issues or optimize the system. The library can help us identify processes that are consuming too many system resources, which can then be killed or optimized for better performance.
In conclusion, monitoring system performance is crucial in ensuring that our systems are running optimally. Python’s psutil library provides a powerful and easy-to-use tool for retrieving system information, which we can use to diagnose performance issues and optimize the system. With this library, we can easily retrieve different types of system information with just a few lines of Python code.
Source Code — https://github.com/rtiwariops/CodeHub/tree/main/hostmon-python