Advertisement
Python253

system_info_collector

May 24th, 2024
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.75 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: system_info_collector.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script collects various system information such as CPU, memory, disk, GPU, and system details.
  10.    - It then formats the collected information as plain text and optionally saves it to a text file.
  11.  
  12. Requirements:
  13.    - Python 3.x
  14.    - psutil
  15.    - GPUtil
  16.  
  17. Functions:
  18.    - get_cpu_info():
  19.        Retrieves CPU information.
  20.    - get_memory_info():
  21.        Retrieves memory information.
  22.    - get_disk_info():
  23.        Retrieves disk information.
  24.    - get_gpu_info():
  25.        Retrieves GPU information.
  26.    - get_system_info():
  27.        Retrieves system information.
  28.    - format_data_as_text(data):
  29.        Formats collected system information as plain text.
  30.    - main():
  31.        Main function to collect and save system information.
  32.  
  33. Usage:
  34.    - Run the script.
  35.    - Follow the on-screen prompts to save the information to a text file if desired.
  36.  
  37. Additional Notes:
  38.    - Ensure that 'psutil' and 'GPUtil' libraries are installed.
  39.    - The script may take some time to collect system information depending on the system's configuration.
  40. """
  41.  
  42. import psutil
  43. import GPUtil
  44. import os
  45.  
  46. def get_cpu_info():
  47.     """Retrieve CPU information.
  48.  
  49.    Returns:
  50.        tuple: A tuple containing a dictionary with CPU information and a boolean indicating success.
  51.    """
  52.     try:
  53.         cpu_info = {
  54.             "Physical Cores": psutil.cpu_count(logical=False),
  55.             "Total Cores": psutil.cpu_count(logical=True),
  56.             "Max Frequency (MHz)": psutil.cpu_freq().max,
  57.             "Min Frequency (MHz)": psutil.cpu_freq().min,
  58.             "Current Frequency (MHz)": psutil.cpu_freq().current,
  59.             "CPU Usage per Core (%)": psutil.cpu_percent(percpu=True),
  60.             "Total CPU Usage (%)": psutil.cpu_percent()
  61.         }
  62.         return cpu_info, True
  63.     except Exception as e:
  64.         return str(e), False
  65.  
  66. def get_memory_info():
  67.     """Retrieve memory information.
  68.  
  69.    Returns:
  70.        tuple: A tuple containing a dictionary with memory information and a boolean indicating success.
  71.    """
  72.     try:
  73.         svmem = psutil.virtual_memory()
  74.         memory_info = {
  75.             "Total Memory (bytes)": svmem.total,
  76.             "Available Memory (bytes)": svmem.available,
  77.             "Used Memory (bytes)": svmem.used,
  78.             "Memory Usage (%)": svmem.percent
  79.         }
  80.         return memory_info, True
  81.     except Exception as e:
  82.         return str(e), False
  83.  
  84. def get_disk_info():
  85.     """Retrieve disk information.
  86.  
  87.    Returns:
  88.        tuple: A tuple containing a list of dictionaries with disk information for each partition and a boolean indicating success.
  89.    """
  90.     try:
  91.         partitions = psutil.disk_partitions()
  92.         disk_info = []
  93.         for partition in partitions:
  94.             partition_info = {
  95.                 "Device": partition.device,
  96.                 "Mountpoint": partition.mountpoint,
  97.                 "File System Type": partition.fstype
  98.             }
  99.             try:
  100.                 partition_usage = psutil.disk_usage(partition.mountpoint)
  101.                 partition_info.update({
  102.                     "Total Size (bytes)": partition_usage.total,
  103.                     "Used Size (bytes)": partition_usage.used,
  104.                     "Free Size (bytes)": partition_usage.free,
  105.                     "Usage (%)": partition_usage.percent
  106.                 })
  107.             except PermissionError:
  108.                 continue
  109.             disk_info.append(partition_info)
  110.         return disk_info, True
  111.     except Exception as e:
  112.         return str(e), False
  113.  
  114. def get_gpu_info():
  115.     """Retrieve GPU information.
  116.  
  117.    Returns:
  118.        tuple: A tuple containing a list of dictionaries with GPU information for each GPU and a boolean indicating success.
  119.    """
  120.     try:
  121.         gpus = GPUtil.getGPUs()
  122.         gpu_info = []
  123.         for gpu in gpus:
  124.             gpu_info.append({
  125.                 "ID": gpu.id,
  126.                 "Name": gpu.name,
  127.                 "Driver Version": gpu.driver,
  128.                 "Total Memory (MB)": gpu.memoryTotal,
  129.                 "Free Memory (MB)": gpu.memoryFree,
  130.                 "Used Memory (MB)": gpu.memoryUsed,
  131.                 "GPU Load (%)": gpu.load * 100,
  132.                 "Temperature (C)": gpu.temperature
  133.             })
  134.         return gpu_info, True
  135.     except Exception as e:
  136.         return str(e), False
  137.  
  138. def get_system_info():
  139.     """Retrieve system information using 'systeminfo' command.
  140.  
  141.    Returns:
  142.        tuple: A tuple containing the system information as a string and a boolean indicating success.
  143.    """
  144.     try:
  145.         system_info = os.popen('systeminfo').read()
  146.         return system_info, True
  147.     except Exception as e:
  148.         return str(e), False
  149.  
  150. def format_data_as_text(data):
  151.     """Format system information data as plain text.
  152.  
  153.    Args:
  154.        data (dict): A dictionary containing various system information.
  155.  
  156.    Returns:
  157.        str: Formatted system information data as plain text.
  158.    """
  159.     formatted_data = []
  160.  
  161.     def add_section(title, info, success):
  162.         formatted_data.append(f"{title}\n" + "="*len(title) + "\n")
  163.         if success:
  164.             if isinstance(info, dict):
  165.                 for key, value in info.items():
  166.                     formatted_data.append(f"{key}: {value}")
  167.             else:
  168.                 formatted_data.append(info)
  169.         else:
  170.             formatted_data.append(f"Error: {info}")
  171.         formatted_data.append("\n")
  172.  
  173.     add_section("CPU Information", *data["cpu_info"])
  174.     add_section("Memory Information", *data["memory_info"])
  175.    
  176.     formatted_data.append("Disk Information\n" + "="*15 + "\n")
  177.     for idx, disk in enumerate(*data["disk_info"]):
  178.         formatted_data.append(f"Disk {idx + 1}\n" + "-"*6)
  179.         for key, value in disk.items():
  180.             formatted_data.append(f"{key}: {value}")
  181.         formatted_data.append("\n")
  182.    
  183.     formatted_data.append("GPU Information\n" + "="*14 + "\n")
  184.     for idx, gpu in enumerate(*data["gpu_info"]):
  185.         formatted_data.append(f"GPU {idx + 1}\n" + "-"*5)
  186.         for key, value in gpu.items():
  187.             formatted_data.append(f"{key}: {value}")
  188.         formatted_data.append("\n")
  189.    
  190.     add_section("System Information", *data["system_info"])
  191.  
  192.     return "\n".join(formatted_data)
  193.  
  194. def main():
  195.     """Main function to collect and save system information."""
  196.     print("\n" + "-" * 60 + "\n\t    Welcome To The System Info Collector\n\n[This may take some time to collect your system information]\n\n\t        Thank you for your patience\n" + "-" * 60)
  197.    
  198.     data = {
  199.         "cpu_info": get_cpu_info(),
  200.         "memory_info": get_memory_info(),
  201.         "disk_info": get_disk_info(),
  202.         "gpu_info": get_gpu_info(),
  203.         "system_info": get_system_info()
  204.     }
  205.    
  206.     print("\n\t       System information collected:\n")
  207.     for info_name, (_, success) in data.items():
  208.         status = "Success" if success else "Failed"
  209.         print(f"\t       - {info_name.ljust(18)}: {status}")
  210.  
  211.     # Check if the user wants to save the data
  212.     save = input("\nWould you like to save this info to a text file? (y/n): ").strip().lower()
  213.     if save == 'y':
  214.         file_name = "system_info.txt"
  215.         formatted_text = format_data_as_text(data)
  216.         with open(file_name, "w", encoding='utf-8') as file:
  217.             file.write(formatted_text)
  218.         print(f"\nFILE: {{{file_name}}} has been saved in the cwd.")
  219.         print("\n" + "-" * 60 + "\n\t       Exiting Program...   Goodbye!\n" + "-" * 60 + "\n")
  220.     else:
  221.         print("\n" + "-" * 60 + "\n\t       Exiting Program...   Goodbye!\n" + "-" * 60 + "\n")
  222.  
  223. if __name__ == "__main__":
  224.     main()
  225.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement