Home Programming Extracting Linux System and Hardware Info Using Python

Extracting Linux System and Hardware Info Using Python

by Roshan Agarwal
extracting system info python

Finding hardware and system information in Linux is a handy and interesting task. We can extract Operating System details, user details, memory details, CPU details, and much more using simple python codes on Linux. Although we can perform many of those things using terminal and bash scripting, python is way more interesting.

As a python lover, we want every task to be done using that language, so extracting system and hardware information with python is a great task. Also, we can learn both Linux and python concurrently. This article will be quite long, so take your time to read the whole article and run each code for better understanding.

You can copy each of the codes in a python IDE and run it. If you don’t have a python IDE or want to compare between IDE, see our guide on the top 10 IDE for Linux. By the way, I am using the VS Code as an IDE for writing code. It is open-source and easy to use. If you want to use Visual Studio Code, see our guide on installing VS code on Linux.

Extracting System Info using Python

In this article, we will develop a program that will extract the following details:

  • Basic System Details
  • CPU Details
  • Memory information
  • Disk Usage
  • Network Information
  • Other Hardware Details

To get these details, we shall use the modules present in the Python standard library. Some of the modules we will be using are OS, platform, etc. I have also put the source code in Github; you can see a demo of the program by downloading from my Github repository and running it.

To follow this tutorial, it is recommended to have the latest python version installed in your system. You can follow our guide on installing python on Linux.

Requirements

Many of the libraries we use in this tutorial are present in the python standard library. We only need to install the package psutil. You can check it by importing it. If you don’t have psutil installed, then you can easily install it using the pip tool. To install pip in our system, we need to run the following command in the terminal.

pip install psutil

Getting Basic System Details

Now that you have installed psutil let’s see how to use it to gather OS using python. We were using the platform module present in the python standard library for gathering this basic system information. You need to copy the following code in your favorite python IDE and run it.

# importing the required modules

import platform

# printing the Architecture of the OS
print("[+] Architecture :", platform.architecture()[0])

# Displaying the machine
print("[+] Machine :", platform.machine())

# printing the Operating System release information
print("[+] Operating System Release :", platform.release())

# prints the currently using system name
print("[+] System Name :",platform.system())

# This line will print the version of your Operating System
print("[+] Operating System Version :", platform.version())

# This will print the Node or hostname of your Operating System
print("[+] Node: " + platform.node())

# This will print your system platform
print("[+] Platform :", platform.platform())

# This will print the processor information
print("[+] Processor :",platform.processor())

In the above code, we first imported the platform module present in the python standard library. After importing the module, we use the platform module’s functions to get the required information. On running the code on my device, I got the following output.

basic system information using python

basic system information using python

As we can see in the output, the program displays many important details about the operating system like system architecture, platform, and much more.

System Uptime

We can also get the system boot time and the system uptime in python. We need to use the psutil library that we have installed earlier. We can get the system uptime by reading the uptime file present in the proc directory in Linux.

Please copy the following code in your favorite python IDE and run it.

from datetime import datetime
import psutil

# Using the psutil library to get the boot time of the system
boot_time = datetime.fromtimestamp(psutil.boot_time())
print("[+] System Boot Time :", boot_time)

This code will print the boot time, meaning the time when the system got booted. On running the program on my PC, I got the following output.

system bootime using python

system boot time using python

We can also see the system uptime, which is the time for which the system is running. We need to read the proc directory’s uptime file, as shown in the below code.

# getting thesystem up time from the uptime file at proc directory
with open("/proc/uptime", "r") as f:
    uptime = f.read().split(" ")[0].strip()

uptime = int(float(uptime))
uptime_hours = uptime // 3600
uptime_minutes = (uptime % 3600) // 60
print("[+] System Uptime : " + str(uptime_hours) + ":" + str(uptime_minutes) + " hours")

I have got the following output on running the code.

system uptime using python

system uptime using python

Processes

We can also use python to get a list of currently running processes, total no of processes. We need to run the following code.

import os

pids = []
for subdir in os.listdir('/proc'):
    if subdir.isdigit():
        pids.append(subdir)
print('Total number of processes : {0}'.format(len(pids)))

On running the code, I got the output, as shown in the below image.

total number of processes

total number of processes

User Information

We can also get the list of all users present in our Linux device using the pwd library present in the python standard library. To do this, you need to copy the following code in your python IDE and run it.

import pwd

users = pwd.getpwall()
for user in users:
    print(user.pw_name, user.pw_shell)

On running the above code, you will get all the users present in your device and their shells.

CPU Information

We have gathered the System Details now to collect some information about the CPU used by our machine. We can gather CPU information from our Linux machine in two ways. The first and easiest way is to use the psutil module and the second way is by reading the file /proc/cpuinfo.

Let us see how we can use the psutil library to get the CPU information. You need to copy the following code into your favorite python IDE and run it.

# importing the required packages
import psutil

# This code will print the number of CPU cores present
print("[+] Number of Physical cores :", psutil.cpu_count(logical=False))
print("[+] Number of Total cores :", psutil.cpu_count(logical=True))
print("\n")
# This will print the maximum, minimum and current CPU frequency
cpu_frequency = psutil.cpu_freq()
print(f"[+] Max Frequency : {cpu_frequency.max:.2f}Mhz")
print(f"[+] Min Frequency : {cpu_frequency.min:.2f}Mhz")
print(f"[+] Current Frequency : {cpu_frequency.current:.2f}Mhz")
print("\n")
# This will print the usage of CPU per core
for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
    print(f"[+] CPU Usage of Core {i} : {percentage}%")
print(f"[+] Total CPU Usage : {psutil.cpu_percent()}%")

Let us see what is happening in the above program. In the first line, we imported the psutil module, which will help gather the CPU details. In the second and third lines, we use the cpu_count() function of the psutil module to count the number of CPU cores. Then we used the cpu_freq() function to get the max, min, and current frequency. At last, we use the cpu_percent function fo psutil to find the CPU usage. On running the code in my machine, I got the following output.

cpu information using psutil

CPU information using psutil

As we can see in the output that all the CPU details have been output by the program in the terminal. We can also get the name of the CPU by reading the file /proc/cpuinfo using python. To do this, we need to run the following code.

# reading the cpuinfo file to print the name of
# the CPU present
with open("/proc/cpuinfo", "r") as f:
    file_info = f.readlines()

cpuinfo = [x.strip().split(":")[1] for x in file_info if "model name" in x]
for index, item in enumerate(cpuinfo):
    print("[+] Processor " + str(index) + " : " + item)

We can also collect other CPU information using the /proc/cpuinfo file. I only read the CPU model name, but you can open the file and see the other information present in the file and can use them in the program. Here’s the output.

cpu information using cpuinfo file

CPU information using cpuinfo file

Let’s gather some information about memory using python.

Memory Information

Like the CPU information, we can also get memory information from two places. One is using the psutil tool, and the second is by reading the proc/meminfo file. To begin with, let us start gathering memory information using the psutil library. Please copy the following code into your favorite python IDE and run it.

# importing the requred modules
import psutil

# writing a function to convert bytes to GigaByte
def bytes_to_GB(bytes):
    gb = bytes/(1024*1024*1024)
    gb = round(gb, 2)
    return gb

# Using the virtual_memory() function it will return a tuple
virtual_memory = psutil.virtual_memory()

#This will print the primary memory details
print("[+] Total Memory present :", bytes_to_GB(virtual_memory.total), "Gb")
print("[+] Total Memory Available :", bytes_to_GB(virtual_memory.available), "Gb")
print("[+] Total Memory Used :", bytes_to_GB(virtual_memory.used), "Gb")
print("[+] Percentage Used :", virtual_memory.percent, "%")
print("\n")

# This will print the swap memory details if available
swap = psutil.swap_memory()
print(f"[+] Total swap memory :{bytes_to_GB(swap.total)}")
print(f"[+] Free swap memory : {bytes_to_GB(swap.free)}")
print(f"[+] Used swap memory : {bytes_to_GB(swap.used)}")
print(f"[+] Percentage Used: {swap.percent}%")

Let us see what is going on in the above code. In the first line, we imported the psutil library, then used its virtual_memory() function, which returns a tuple with virtual memory information. Then we use the swap_memory() function to get the information of the swap memory. We also built a function name bytes_to_GB(), which will convert the bytes into GigaBytes for better readability. I got the following output.

memory information using psutil

memory information using psutil

We can also use the meminfo file present in Linux’s proc directory to retrieve memory information like total memory, memory used, etc. To do this, run the following code.

# Gathering memory information from meminfo file
print("\nReading the /proc/meminfo file: \n")
with open("/proc/meminfo", "r") as f:
    lines = f.readlines()

print("[+] " + lines[0].strip())
print("[+] " + lines[1].strip())

And here is the output:

memory information using meminfo file

Disk Information

Till now, we have seen some basic system details, CPU details, Memory details. Now let us see the information about the disk present in our machine. To extract disk information, we will use the psutil module to make our task easy, and we don’t need to reinvent the wheel. Look at the below code to see a working example of the code. You can copy the code and run in your favorite python’s IDE.

# importing required modules
import psutil

# accessing all the disk partitions
disk_partitions = psutil.disk_partitions()

# writing a function to convert bytes to Giga bytes
def bytes_to_GB(bytes):
    gb = bytes/(1024*1024*1024)
    gb = round(gb, 2)
    return gb

# displaying the partition and usage information
for partition in disk_partitions:
    print("[+] Partition Device : ", partition.device)
    print("[+] File System : ", partition.fstype)
    print("[+] Mountpoint : ", partition.mountpoint)
    
    disk_usage = psutil.disk_usage(partition.mountpoint)
    print("[+] Total Disk Space :", bytes_to_GB(disk_usage.total), "GB")
    print("[+] Free Disk Space :", bytes_to_GB(disk_usage.free), "GB")
    print("[+] Used Disk Space :", bytes_to_GB(disk_usage.used), "GB")
    print("[+] Percentage Used :", disk_usage.percent, "%")

# get read/write statistics since boot
disk_rw = psutil.disk_io_counters()
print(f"[+] Total Read since boot : {bytes_to_GB(disk_rw.read_bytes)} GB")
print(f"[+] Total Write sice boot : {bytes_to_GB(disk_rw.write_bytes)} GB")

In the code, we have first imported the psutil library, which is required to gather the disk information. Then we used its disk_partitions() function to get the list of disk partitions available with their information. We also use the disk_usage() function to get the usage of these partitions. Finally, we use the disk_io_counters() function to get the disk’s total read/to write since boot.  Here is an example output.

disk information using python

You may get some other output depending on your disk and partitions.

Network Information

We can also gather the network information of the system using the psutil library. To do so, copy the following code into your python IDE and run it.

# importing the required modules
import psutil

# writing a function to convert the bytes into gigabytes
def bytes_to_GB(bytes):
    gb = bytes/(1024*1024*1024)
    gb = round(gb, 2)
    return gb

# gathering all network interfaces (virtual and physical) from the system
if_addrs = psutil.net_if_addrs()

# printing the information of each network interfaces
for interface_name, interface_addresses in if_addrs.items():
    for address in interface_addresses:
        print("\n")
        print(f"Interface :", interface_name)
        if str(address.family) == 'AddressFamily.AF_INET':
            print("[+] IP Address :", address.address)
            print("[+] Netmask :", address.netmask)
            print("[+] Broadcast IP :", address.broadcast)
        elif str(address.family) == 'AddressFamily.AF_PACKET':
            print("[+] MAC Address :", address.address)
            print("[+] Netmask :", address.netmask)
            print("[+] Broadcast MAC :",address.broadcast)

# getting the read/write statistics of network since boot
print("\n")
net_io = psutil.net_io_counters()
print("[+] Total Bytes Sent :", bytes_to_GB(net_io.bytes_sent))
print("[+] Total Bytes Received :", bytes_to_GB(net_io.bytes_recv))

Here is an example output from my test PC.

network information using python

network information using python

Other Hardware Information

We can also use the psutil library to get some other hardware information like battery information, fans rotating speed, various devices’ temperature information, etc. Let us see how we can do this one by one.

If you are using a laptop, then you can use the psutil.sensors_battery() function to get the battery information. To do so, copy and run the following code in your Python IDE.

import psutil

battery = psutil.sensors_battery()
print("[+] Battery Percentage :", round(battery.percent, 1), "%")
print("[+] Battery time left :", round(battery.secsleft/3600, 2), "hr")
print("[+] Power Plugged :", battery.power_plugged)

In the above code, we use the sensors_battery() function to get the battery’s information, such as battery percentage, remaining time, power plugged, or not. On running the code in my machine, I got the following output.

battery information using python

battery information using python

We can also use the psutil library to get the fan’s RPM (Revolutions Per Minute) using the function  sensors_fan() while the fan is running. The psutil can also be used to get the temperature of various devices. We can do it using the sensors_temperatures() function of the psutil. I am leaving this to be done by you for practice.

Final Script

Now let us combine all the codes with building a final program to gather all the system and hardware details that we discussed. You can copy the following program and run it in your python IDE.

# importing the required modules
import platform
from datetime import datetime
import psutil
import os

# First We will print the basic system information
# using the platform module

print("\n\t\t\t Basic System Information\n")
print("[+] Architecture :", platform.architecture()[0])
print("[+] Machine :", platform.machine())
print("[+] Operating System Release :", platform.release())
print("[+] System Name :",platform.system())
print("[+] Operating System Version :", platform.version())
print("[+] Node: " + platform.node())
print("[+] Platform :", platform.platform())
print("[+] Processor :",platform.processor())

# Using the psutil library to get the boot time of the system
boot_time = datetime.fromtimestamp(psutil.boot_time())
print("[+] System Boot Time :", boot_time)
# getting the system up time from the uptime file at proc directory

with open("/proc/uptime", "r") as f:
    uptime = f.read().split(" ")[0].strip()

uptime = int(float(uptime))
uptime_hours = uptime // 3600
uptime_minutes = (uptime % 3600) // 60
print("[+] System Uptime : " + str(uptime_hours) + ":" + str(uptime_minutes) + " hours")

# getting the total number of processes currently running
pids = []
for subdir in os.listdir('/proc'):
    if subdir.isdigit():
        pids.append(subdir)
print('Total number of processes : {0}'.format(len(pids)))

# Displaying The CPU information
print("\n\t\t\t CPU Information\n")

# This code will print the number of CPU cores present
print("[+] Number of Physical cores :", psutil.cpu_count(logical=False))
print("[+] Number of Total cores :", psutil.cpu_count(logical=True))
print("\n")

# This will print the maximum, minimum and current CPU frequency
cpu_frequency = psutil.cpu_freq()
print(f"[+] Max Frequency : {cpu_frequency.max:.2f}Mhz")
print(f"[+] Min Frequency : {cpu_frequency.min:.2f}Mhz")
print(f"[+] Current Frequency : {cpu_frequency.current:.2f}Mhz")
print("\n")

# This will print the usage of CPU per core
for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
    print(f"[+] CPU Usage of Core {i} : {percentage}%")
    print(f"[+] Total CPU Usage : {psutil.cpu_percent()}%")

# reading the cpuinfo file to print the name of
# the CPU present

with open("/proc/cpuinfo", "r") as f:
    file_info = f.readlines()

cpuinfo = [x.strip().split(":")[1] for x in file_info if "model name" in x]

for index, item in enumerate(cpuinfo):
    print("[+] Processor " + str(index) + " : " + item)

# writing a function to convert bytes to GigaByte
def bytes_to_GB(bytes):
    gb = bytes/(1024*1024*1024)
    gb = round(gb, 2)
    return gb

# Using the virtual_memory() function it will return a tuple
virtual_memory = psutil.virtual_memory()
print("\n\t\t\t Memory Information\n")
#This will print the primary memory details
print("[+] Total Memory present :", bytes_to_GB(virtual_memory.total), "Gb")
print("[+] Total Memory Available :", bytes_to_GB(virtual_memory.available), "Gb")
print("[+] Total Memory Used :", bytes_to_GB(virtual_memory.used), "Gb")
print("[+] Percentage Used :", virtual_memory.percent, "%")
print("\n")

# This will print the swap memory details if available
swap = psutil.swap_memory()
print(f"[+] Total swap memory :{bytes_to_GB(swap.total)}")
print(f"[+] Free swap memory : {bytes_to_GB(swap.free)}")
print(f"[+] Used swap memory : {bytes_to_GB(swap.used)}")
print(f"[+] Percentage Used: {swap.percent}%")

# Gathering memory information from meminfo file

print("\nReading the /proc/meminfo file: \n")
with open("/proc/meminfo", "r") as f:
    lines = f.readlines()
print("[+] " + lines[0].strip())
print("[+] " + lines[1].strip())

# accessing all the disk partitions
disk_partitions = psutil.disk_partitions()
print("\n\t\t\t Disk Information\n")

# displaying the partition and usage information
for partition in disk_partitions:
    print("[+] Partition Device : ", partition.device)
    print("[+] File System : ", partition.fstype)
    print("[+] Mountpoint : ", partition.mountpoint)
    
    disk_usage = psutil.disk_usage(partition.mountpoint)
    print("[+] Total Disk Space :", bytes_to_GB(disk_usage.total), "GB")
    print("[+] Free Disk Space :", bytes_to_GB(disk_usage.free), "GB")
    print("[+] Used Disk Space :", bytes_to_GB(disk_usage.used), "GB")
    print("[+] Percentage Used :", disk_usage.percent, "%")

# get read/write statistics since boot
disk_rw = psutil.disk_io_counters()
print(f"[+] Total Read since boot : {bytes_to_GB(disk_rw.read_bytes)} GB")
print(f"[+] Total Write sice boot : {bytes_to_GB(disk_rw.write_bytes)} GB")

# gathering all network interfaces (virtual and physical) from the system
if_addrs = psutil.net_if_addrs()
print("\n\t\t\t Network Information\n")
# printing the information of eah network interfaces
for interface_name, interface_addresses in if_addrs.items():
    for address in interface_addresses:
        print(f"Interface :", interface_name)
        if str(address.family) == 'AddressFamily.AF_INET':
            print("[+] IP Address :", address.address)
            print("[+] Netmask :", address.netmask)
            print("[+] Broadcast IP :", address.broadcast)
        elif str(address.family) == 'AddressFamily.AF_PACKET':
            print("[+] MAC Address :", address.address)
            print("[+] Netmask :", address.netmask)
            print("[+] Broadcast MAC :",address.broadcast)

# getting the read/write statistics of network since boot
net_io = psutil.net_io_counters()
print("[+] Total Bytes Sent :", bytes_to_GB(net_io.bytes_sent))
print("[+] Total Bytes Received :", bytes_to_GB(net_io.bytes_recv))

# Getting The battery Information
battery = psutil.sensors_battery()
print("\n\t\t\t Battery Information\n")
print("[+] Battery Percentage :", round(battery.percent, 1), "%")
print("[+] Battery time left :", round(battery.secsleft/3600, 2), "hr")
print("[+] Power Plugged :", battery.power_plugged)

On running this code, we will get the following output.

a tool to extract system and hardware information using python

a tool to extract system and hardware information using python

If you want to improve the program or want to download the code, you can do it from my Github page.

Conclusion

This is the full tutorial on gathering some interesting system and hardware information using python. If you have any problem with copying the code, you can also find the full source code in my Github repo. You may also want to see our guide on working with Operating System in python for some more interesting python tweaks.

You may also like

1 comment

luis August 4, 2022 - 1:18 AM

thanks

Reply

Leave a Comment

fl_logo_v3_footer

ENHANCE YOUR LINUX EXPERIENCE.



FOSS Linux is a leading resource for Linux enthusiasts and professionals alike. With a focus on providing the best Linux tutorials, open-source apps, news, and reviews written by team of expert authors. FOSS Linux is the go-to source for all things Linux.

Whether you’re a beginner or an experienced user, FOSS Linux has something for everyone.

Follow Us

Subscribe

©2016-2023 FOSS LINUX

A PART OF VIBRANT LEAF MEDIA COMPANY.

ALL RIGHTS RESERVED.

“Linux” is the registered trademark by Linus Torvalds in the U.S. and other countries.