How To Monitor your Devices in Python

  • CPU
  • Memory -RAM, Swap space, and Hard disk space
  • Network usage
  • GPU usage
  • Linux
  • Windows
  • macOS
  • FreeBSD, OpenBSD, NetBSD
  • Sun Solaris
  • AIX

System profile

import psutil
import platform
uname = platform.uname()

print(f"System: {uname.system}") #Windows or Linux
print(f"Node Name: {uname.node}") # System name
print(f"Release: {uname.release}") # OS release version like 10(Windows) or 5.4.0-72-generic(linux)
print(f"Version: {uname.version}")
print(f"Machine: {uname.machine}") # machine can be AMD64 or x86-64
print(f"Processor: {uname.processor}") # Intel64 Family 6 or x86_64
print("Physical cores:", psutil.cpu_count(logical=False))
print("Total cores:", psutil.cpu_count(logical=True))
# CPU frequencies
cpufreq = psutil.cpu_freq()
print(f"Max Frequency: {cpufreq.max:.2f}Mhz")
print(f"Min Frequency: {cpufreq.min:.2f}Mhz")
print(f"Current Frequency: {cpufreq.current:.2f}Mhz")

Monitoring and Limiting CPU Resources

for i in range(len(psutil.sensors_temperatures(fahrenheit=True)[ 'coretemp'])):
print(str(psutil.sensors_temperatures(fahrenheit=True)[ 'coretemp'][i].label) + " has a temp of " + str(psutil.sensors_temperatures(fahrenheit=True)[ 'coretemp'][i].current) + "F")
if psutil.sensors_temperatures(fahrenheit=True)[ 'coretemp'][i].current >psutil.sensors_temperatures(fahrenheit=True)[ 'coretemp'][i].high:
print("Temp too high")

Monitoring and Limiting Memory

def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format- KB, MB, GB, TB and PB
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{bytes:.2f}{unit}{suffix}"
bytes /= factorprint("Virtual memory")
svmem = psutil.virtual_memory()
print(f"Total: {get_size(svmem.total)}")
print(f"Available: {get_size(svmem.available)}")
print(f"Used: {get_size(svmem.used)}")
print(f"Percentage: {svmem.percent}%")

print("SWAP memory")
# get the swap memory details (if exists)
swap = psutil.swap_memory()
print(f"Total: {get_size(swap.total)}")
print(f"Free: {get_size(swap.free)}")
print(f"Used: {get_size(swap.used)}")
print(f"Percentage: {swap.percent}%")

Limiting Threshold on virtual memory and swap memory

VIRTUAL_MEMEORY_THRESHOLD = 100 * 1024 * 1024  # 100MB
SWAP_MEMEORY_THRESHOLD = 45
if psutil.virtual_memory().available <= THRESHOLD:
print("Low Virtual Memory warning")
if psutil.swap_memory().percent>=SWAP_MEMEORY_THRESHOLD:
print("Low Swap Memory warning")

Monitoring and Limiting Hard Disk Space

print( "Hard Disk Information")
print("Partitions and Usage:")

# get all disk partitions on the device
partitions = psutil.disk_partitions()
for partition in partitions:
print("Device:",partition.device)
print("Partition Mountpoint: ",partition.mountpoint)
print("Partition File system type",partition.fstype)
try:
partition_usage = psutil.disk_usage(partition.mountpoint)
except PermissionError:
continue
print("Total Size: ", get_size(partition_usage.total))
print("Used Space: ", get_size(partition_usage.used))
print("Free hard disk Space", get_size(partition_usage.free))
print("Hard disk Used Percentage: ", partition_usage.percent, "%")
if(partition_usage.percent >82):
print("Disk space nearing full")

Monitoring and Limiting Network Usage

  • AF_INET: IPv4 Internet protocols
  • AF_INET6: IPv6 Internet protocols
  • AF_NETLINK: Kernel user interface device
  • AF_PACKET: Low-level packet interface
print( "Network Information")
# get all network interfaces (virtual and physical)
if_addrs = psutil.net_if_addrs()
for interface_name, interface_addresses in if_addrs.items():
for address in interface_addresses:
print(" Interface: ", interface_name)
if str(address.family) == 'AddressFamily.AF_INET':
print(" IP Address: ", address.address)
print(" Netmask: ", address.netmask)
print(" Broadcast IPv4: ",address.broadcast)
elif str(address.family) == 'AddressFamily.AF_PACKET':
print(" MAC Address: {address.address}")
print(" Netmask: {address.netmask}")
print(" Broadcast MAC: {address.broadcast}")
elif str(address.family) == 'AddressFamily.AF_INET6':
print(" IP Address: ", address.address)
print(" Netmask: ", address.netmask)
print(" Broadcast IPv6: ",address.broadcast)
net_io = psutil.net_io_counters()
print("Total Bytes Sent: ", get_size(net_io.bytes_sent))
print("Total Bytes Received: ", get_size(net_io.bytes_recv))
print("Total outgoing packets dropped: ", net_io.dropin)
print("Total incoming packets dropped:", net_io.dropout)
print("Total outgoing errors: ", net_io.errout)
print("Total incoming errors:", net_io.errin)

Monitoring GPU

import GPUtil
Gpus = GPUtil.getGPUs()
gpulist=[]
for gpu in Gpus:
print(gpu.name)
print('gpu.id:', gpu.id)

print ( 'total GPU:', gpu.memoryTotal)
print(f"Memory free {gpu.memoryFree}MB")
print ( 'GPU usage:', gpu.memoryUsed)
print ( 'gpu use proportion:', gpu.memoryUtil * 100)
print(str(gpu.temperature) + " C")

gpulist.append([ gpu.id, gpu.memoryTotal, gpu.memoryUsed,gpu.memoryUtil * 100])

THRESHOLD_GPU=10
for gpu in Gpus:
print(gpu.name,' gpu.id:', gpu.id)
if gpu.memoryTotal/gpu.memoryUsed*100>THRESHOLD_GPU:print ( f"gpu memory usgae currently is: {gpu.memoryUtil * 100}% which exceeds the threshold of {THRESHOLD_GPU}%" )

Monitoring Sensors

psutil.sensors_temperatures()
psutil.sensors_fans()
psutil.sensors_battery()

Conclusion:

--

--

--

Data Analysis and ML| UI Designer | Python |Tableau |AR |Arduino |React Native

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Safe Way To Download Adobe Flash Player For Mac

Road to coding interview (Day 4)

Setting up an Apla Ecosystem

Introducing: S3 Security Visualizer

Setting up local ethereum test net

ZafGod — Artist of the Month #2

Promises and Async/Await

How To Start Contributing to Mozilla

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akash Singh

Akash Singh

Data Analysis and ML| UI Designer | Python |Tableau |AR |Arduino |React Native

More from Medium

Optimize problems using Simplex Method and Python

How to convert text to graph with python?

The perfect day at Walt Disney World: Finding an optimal route through Magic Kingdom using Python

Power of Python