Detect and Fix Issues Early: A Python Guide to System Diagnostics
By Ed Malaker
Running complete diagnostics on your computer every few weeks can be a great way to be sure your system is running at optimal performance, and it can help you detect problems early. In this guide, we’ll show you how to use Python to scan your system easily, giving you insight into your hardware, software, network, and security.
Script Overview
The Python script we are creating will check the following things:
- Basic system information
- Monitor CPU and memory usage
- Check disk usage and health
- Assess network connectivity and speed
- Verify the presence of security updates and scan for malware
- Check for updates to installed software
Complete Script
import os
import platform
import psutil
import subprocess
import requests
def get_system_info():
"""Gather basic system information."""
print("Gathering system information...")
sys_info = {
"OS": platform.system(),
"OS Version": platform.version(),
"Platform": platform.platform(),
"Processor": platform.processor(),
"Architecture": platform.architecture(),
"Hostname": platform.node(),
}
for key, value in sys_info.items():
print(f"{key}: {value}")
def get_cpu_memory_usage():
"""Monitor CPU and memory usage."""
print("\nMonitoring CPU and memory usage...")
print(f"CPU Usage: {psutil.cpu_percent(interval=1)}%")
print(f"Memory Usage: {psutil.virtual_memory().percent}%")
def get_disk_usage():
"""Check disk usage and health."""
print("\nChecking disk usage and health...")
partitions = psutil.disk_partitions()
for partition in partitions:
usage = psutil.disk_usage(partition.mountpoint)
print(f"Partition: {partition.device}")
print(f" Mountpoint: {partition.mountpoint}")
print(f" File system type: {partition.fstype}")
print(f" Total Size: {usage.total // (2**30)} GiB")
print(f" Used: {usage.used // (2**30)} GiB")
print(f" Free: {usage.free // (2**30)} GiB")
print(f" Usage: {usage.percent}%")
def get_network_status():
"""Assess network connectivity and speed."""
print("\nAssessing network connectivity and speed...")
hostname = "google.com"
response = os.system(f"ping -c 1 {hostname}")
if response == 0:
print(f"{hostname} is reachable")
else:
print(f"{hostname} is not reachable")
try:
import speedtest
st = speedtest.Speedtest()
st.download()
st.upload()
st.results.share()
results = st.results.dict()
print(f"Download Speed: {results['download'] / 1_000_000:.2f} Mbps")
print(f"Upload Speed: {results['upload'] / 1_000_000:.2f} Mbps")
except ImportError:
print("Speedtest module not installed. Install it using 'pip install speedtest-cli'")
def check_security_updates():
"""Verify the presence of security updates."""
print("\nVerifying the presence of security updates...")
if platform.system() == "Windows":
subprocess.run(["powershell", "Get-WindowsUpdate"])
elif platform.system() == "Linux":
os.system("sudo apt update && sudo apt upgrade -s")
else:
print("Security update check not supported for this OS.")
def scan_for_malware():
"""Scan for malware."""
print("\nScanning for malware...")
if platform.system() == "Windows":
subprocess.run(["powershell", "Start-MpScan -ScanType QuickScan"])
elif platform.system() == "Linux":
os.system("sudo clamscan -r /")
else:
print("Malware scan not supported for this OS.")
def check_software_updates():
"""Check for updates to installed software."""
print("\nChecking for software updates...")
if platform.system() == "Windows":
subprocess.run(["powershell", "Get-Package -ProviderName Programs | ForEach-Object { $_.Name; Get-Package -ProviderName Programs -Name $_.Name -IncludeWindowsInstaller -AllVersions | ForEach-Object { $_.Name, $_.Version } }"])
elif platform.system() == "Linux":
os.system("apt list --upgradable")
else:
print("Software update check not supported for this OS.")
if __name__ == "__main__":
get_system_info()
get_cpu_memory_usage()
get_disk_usage()
get_network_status()
check_security_updates()
scan_for_malware()
check_software_updates()
Script Explanation
System Information
Python will use the platform module to gather details about the operating system, processor, and architecture.
CPU and Memory Usage
Pythons psutil library provides the functions to retrieve CPU and memory usage statistics.
Disk Usage
The psutil library also provides the functions to retrieve information about disc usage through psutil.disk_partitions() and psutil.disk_usage()
Network Status
The script uses os.system to ping a well-known host (google.com) and checks network reachability while the speed test library measures internet speed.
Security Updates
The script runs platform-specific commands to check for security updates on Windows and Linux.
Malware Scan
Python will use Powershell to run a malware scan in Windows, and Clamscan will do the work in Linux.
Software Updates
The script runs platform-specific commands to list available software updates.
Frequently Asked Questions
How Often Should I Run Diagnostics on My Computer?
It’s a good idea to run diagnostics frequently on your computer so you can keep track of how much remaining space you have available on your hard drive. Keeping an eye on your internet speeds can alert you to any problems with your service provider, and keeping your software updated will ensure that you have all of the latest security patches.
How Can I Monitor System Performance over Time Using Python?
It’s best to keep a log of your results by copying and pasting them into a document or having Python print them out for you with a simple script. Some things, like storage space, only need to be checked occasionally, while CPU usage benefits from frequent checking over a short period to see how your processing power gets used.
Can I Have Python Run Diagnostics on Startup?
Yes. You can create a shortcut to your diagnostics script in the startup folder in Windows or the crontab with the @reboot directive in Linux.