I recently finished the Google IT Automation with Python Professional Certificate course on Coursera. Really enjoyable. I recommend it for any python programmers who want to get some hands-on experience of playing with python combined with bash, regex, and the os.

It’s well put together and the final project required some nifty code. I struggled with the system health checks, so I’ve added some of the key lines from the code for future reference.

The key libraries are psutil, shutil, and sockets.

psutil#

The psutil (process and system utilities) library retrieves information on the processes running and the system utilization. This includes CPU, disks, and networks. Below I use it to monitor the CPU usage and Virtual memory availability.

import psutil


# Warning if CPU usage > 80%
def cpu_check():
    cpu_usage = psutil.cpu_percent(1)
    return not cpu_usage > 80


# Warn if available memory less than 500MB
def available_memory_check():
    available = psutil.virtual_memory().available
    available_in_MB = available / 1024 ** 2  #convert to MB
    return available_in_MB > 500

shutil#

The shutil library provides me here with the mechanism to monitor disk_usage.

shutil official docs

import shutil


# Warn if available disk space less than 20%
def disc_space_check():  
    disk_usage = shutil.disk_usage("/")
    disk_total = disk_usage.total
    disk_free = disk_usage.used
    threshold = disk_free / disk_total * 100
    return threshold > 20

socket#

The socket library is used to check if the hostname resolves to the correct IP address.

import socket


# Warn if hostname "localhost" cannot be resolved to "127.0.0.1"
def hostname_check():
    local_host_ip = socket.gethostbyname('localhost')
    return local_host_ip == "127.0.0.1"

Hope that’s of help, future David, and any others out there.