Get Hardware and System Information Using Python

Introduction

In this tutorial, You will learn how to get hardware and system information using python. Python offers two modules, platform, and psutil. Using these two modules we will find many information about our system. Both modules work on a cross-platform. So whatever operating system(Linux, Windows, or Mac) you are running, it will work perfectly for all of them👍.

You can find some basic information using the platform module but psutil offers many functions to get more information about a computer or system in detail. We will use both here.

Let's look a glimpse at which details we're going to find here through several python programs.

🍁Learn AlsoExtract Emails and Phone Numbers🔍 from a WebPage or Text: using Python Regex

The information we will find here

  • Basic Hardware and System Information
    • OS name,
    • Node name,
    • Version,
    • Processor,
    • Architecture, etc.
  • Information about the users
    • Current user,
    • Total users of a system
  • Boot Time
  • CPU Information
    • CPU count,
    • CPU frequency,
    • CPU usage of process,
    • CPU statistics, etc.
  • Memory Information
    • RAM size,
    • RAM usage,
    • Free Space,
    • SWAP memory details, etc.
  • Disk information
    • Total size,
    • Free space,
    • Total read & write since boot time, etc.
  • Network Information
    • Network usage
    • Logical & Physical addresses, etc.
  • Details about running process
    • Total running processes,
    • parent ids, child processes ids of a process, etc.

Get the Basic System Information

First we will try with the platform module to get only the basic information of any computer.

Code


'''Get Hardware and System information using Python'''
import platform

my_pc = platform.uname()

print("\n")
print(f"Operating System: {my_pc.system}")

print(f"Node Name: {my_pc.node}")

print(f"Release: {my_pc.release}")

print(f"Version: {my_pc.version}")

print(f"Machine: {my_pc.machine}")

print(f"Processor: {my_pc.processor}")

print(f"Architecture: {platform.architecture}")

print("\n")

Output

Get basic system information using the python platfrom module.

User Information

Now find the user information of any system. The psutil.user() function returns a list, containing username, host-name, PID, etc.

User

Code


import psutil

print("*"*20, "User Details", "*"*20)
print(psutil.users())

Output

Get user information of any computer using a python program.

Boot Time

Boot Time: the time when the system was turned on. The psutil.boot_time() function returns the boot time in a compact form. We need to convert it into a human-readable format using the datetime.fromtimestamp() function.

Code


import psutil

from datetime import datetime

# Get the boot time
print("*"*20, "Boot Time", "*"*20)
bootTime = psutil.boot_time()
time = datetime.fromtimestamp(bootTime)

print(f"Your Boot Time is: {time.day}/{time.month}/{time.year} \
{time.hour}:{time.minute}:{time.second}")

Output

Get the boot time of any computers using python program.

CPU Information

Now get your CPU information through several functions of the psutil module.

CPU chip

The psutil.cpu_count() function returns the total number of CPU cores. psutil.cpu_freq() returns the current, minimum, and maximum frequency of the CPU and the value, it represents in megahertz(MHz).

psutil.cpu_stats(): for CPU statistics. For example, the number of software interrupts, switches, system calls, etc.

Code


import psutil

# CPU count
print("*"*20, "CPU Core", "*"*20)

print("Total Cores:", psutil.cpu_count())
print("Physical Cores:", psutil.cpu_count(False))

# CPU Frequency
print("*"*20, "Frequency", "*"*20)

frequency = psutil.cpu_freq()
print(f"Current Frequency: {frequency.current:.2f}MHz")
print(f"Min Frequency: {frequency.min}MHz")
print(f"Max Frequency: {frequency.max}MHz")

# CPU usage
print("*"*20, "CPU Usage", "*"*20)

print(f"Total CPU Usage: {psutil.cpu_percent()}%")
for x, prc in enumerate(psutil.cpu_percent\
(interval=1,percpu=True)):
print(f"Core {x}: {prc}%")

print("*"*17, "CPU Statistics", "*"*17)

# CPU Statistics
stats = psutil.cpu_stats()
print(f"Switches: {stats.ctx_switches}")
print(f"Interrupts: {stats.interrupts}")
print(f"Software Interrupts: {stats.soft_interrupts}")
print(f"System Calls: {stats.syscalls}")

Output

Know about your CPU details using a python program. The psutil module has used in this program.

Memory Information

Here we will write a program to get the information about the Main Memory. psutil.virtual_memory() returns the information about a RAM. For instance, RAM size, available space, used space and percentage, etc.

RAM or Main Memory

Here, I've used a function, size_converter() to make the space information in a more readable format. Like KB, MB, GB, etc. as needed. Because all the functions return details about spaces in the byte form and it's not convenient for humans to grip the actual message.

Code


import psutil

def size_converter(size):
# 2**10 = 1024
i = 0
num = 2**10
units = {0 : '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}

while size > num:
size /= num
i += 1
return f"{size:.2f}{units[i]}{'B'}"

# Memory Information
print("*"*20, "Memory Information", "*"*20)
mem = psutil.virtual_memory()

print(f"Total: {size_converter(mem.total)}")
print(f"Available: {size_converter(mem.available)}")
print(f"Used: {size_converter(mem.used)}")
print(f"Percentage: {mem.percent}%")

# Information of the swap memory
print("*"*20, "SWAP Memory", "*"*20)
swap = psutil.swap_memory()

print(f"Total: {size_converter(swap.total)}")
print(f"Free: {size_converter(swap.free)}")
print(f"Used: {size_converter(swap.used)}")
print(f"Percentage: {swap.percent}%")

Output

Get internal memory or RAM information using a python program.

Disk Information

This program will find the details of the external storage(HDD or SSD). For example, total space, available space, used space, total read and write, etc.

Hard Disk

Code


"""Get Disk Information"""
import psutil

def size_converter(size):
# 2**10 = 1024
i = 0
num = 2**10
units = {0 : '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}

while size > num:
size /= num
i += 1
return f"{size:.2f}{units[i]}{'B'}"


print("*"*20, "Disk Information", "*"*20)

# Total Disk Usage
totalUsage = psutil.disk_usage('/')
print(f"Total Size: {size_converter(totalUsage.total)}")
print(f"Used: {size_converter(totalUsage.used)}")
print(f"Free: {size_converter(totalUsage.free)}")
print(f"Percentage: {totalUsage.percent}")

# Get I/O statistics
disk_io = psutil.disk_io_counters()
print(f"Total read: {size_converter(disk_io.read_bytes)}")
print(f"Total write: {size_converter(disk_io.write_bytes)}")

Output

Find the information about your external storage using a python program.

Network Information

psutil.net_io_counters(): returns the information of network usage. For example, total data sent and received, etc.

wireless wifi sign

psutil.net_if_addrs(): returns the details of logical, physical, broadcast addresses, netmask, etc.

Code


import psutil

def size_converter(size):
i = 0
num = 2**10
units = {0 : '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}

while size > num:
size /= num
i += 1
return f"{size:.2f}{units[i]}{'B'}"

# Network Usage
i_o = psutil.net_io_counters()
print(f"Total Data Sent: {size_converter(i_o.bytes_sent)}")
print(f"Total Data Received: {size_converter(i_o.bytes_recv)}")
print(f"Total Packets Sent: {i_o.packets_sent}")
print(f"Total Packets recived: {i_o.packets_recv}")

# Details of physical, logical network address,
# netmask, broadcast address, etc.
print("\n")
print(psutil.net_if_addrs())

Output

Get network interface card details using python

Get the Details about Running Processes

The psutil module provides a function named pids() which returns a list, containing all the process ids that are currently running on the system. 

psutil.Process() gives the information of a specific process. For example, parent ids, child processes ids, etc. You need to mention the PID as an argument to the function.

Code


"""Get the information about the
running processes"""
import psutil

process_id = psutil.pids()
counter = 0
for i in process_id:
counter += 1

print("Total Running Processes: ", counter)

# Get the information of a specific process
# 2646 is a process number.
process = psutil.Process(2646)
print(f"Process Name: {process.name()}")
print(f"Path: {process.exe()}")
print(f"Current directory: {process.cwd()}")
print(f"Command Line: {process.cmdline()}")

print("\n", "*"*20, "Parent Informations", "*"*20)
print(f"Parent Id: {process.ppid()}")
print(f"Parent Details: {process.parent()}")
print(f"ALl Parents: {process.parents()}")

print("\n", "*"*20, "Child Informations", "*"*20)
print(f"Child Processes: {process.children(recursive = True)}")

Output

Get details about running process on a computer using python.

🍁Learn AlsoPython Keylogger - Build a Simple Keylogger in Python

Conclusion

In this tutorial, you learned how to get hardware and system information using python programs. We used two python modules here. One is platform module and another one is psutil. I've covered so many examples for getting several information about hardware and software both. I hope this tutorial will help you a lot. If you've any queries, let me know in the comment section below. I will reply to you soon.

Thanks for reading!💙

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post