Advertisement
Python253

psutil_checks

Apr 6th, 2024
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.57 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: psutil_checks.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script performs various system checks using the psutil library and saves the collected data to a file.
  9. """
  10.  
  11. import psutil
  12.  
  13. def get_cpu_usage():
  14.     """
  15.    Get the current CPU usage percentage.
  16.  
  17.    Returns:
  18.        float: The CPU usage percentage.
  19.    """
  20.     return psutil.cpu_percent(interval=1)
  21.  
  22. def get_system_memory_statistics():
  23.     """
  24.    Get the system memory statistics.
  25.  
  26.    Returns:
  27.        dict: A dictionary containing system memory statistics.
  28.    """
  29.     return psutil.virtual_memory()
  30.  
  31. def get_disk_partitions():
  32.     """
  33.    Get the disk partitions.
  34.  
  35.    Returns:
  36.        list: A list of disk partitions.
  37.    """
  38.     return psutil.disk_partitions()
  39.  
  40. def get_disk_usage(partition='/'):
  41.     """
  42.    Get the disk usage statistics.
  43.  
  44.    Args:
  45.        partition (str): The disk partition to check. Default is '/'.
  46.  
  47.    Returns:
  48.        tuple: A tuple containing disk usage statistics.
  49.    """
  50.     return psutil.disk_usage(partition)
  51.  
  52. def get_connected_users():
  53.     """
  54.    Get information about currently connected users.
  55.  
  56.    Returns:
  57.        list: A list of connected users.
  58.    """
  59.     return psutil.users()
  60.  
  61. def get_system_utilization():
  62.     """
  63.    Get various system utilization metrics.
  64.  
  65.    Returns:
  66.        dict: A dictionary containing system utilization metrics.
  67.    """
  68.     system_util = {
  69.         "CPU Times Percent": psutil.cpu_times_percent(),
  70.         "Logical CPU Count": psutil.cpu_count(),
  71.         "CPU Frequency": psutil.cpu_freq(),
  72.         "Network I/O Statistics": psutil.net_io_counters(),
  73.         "Network Connections": psutil.net_connections(),
  74.         "System Boot Time": psutil.boot_time()
  75.     }
  76.     return system_util
  77.  
  78. def get_miscellaneous():
  79.     """
  80.    Get miscellaneous system information.
  81.  
  82.    Returns:
  83.        dict: A dictionary containing miscellaneous system information.
  84.    """
  85.     test_suite_result = psutil.test()
  86.     misc_info = {}
  87.     if test_suite_result is not None:
  88.         misc_info["psutil Test Suite"] = test_suite_result
  89.     return misc_info
  90.  
  91. def get_process_info():
  92.     """
  93.    Get information about running processes.
  94.  
  95.    Returns:
  96.        list: A list of dictionaries containing process information.
  97.    """
  98.     processes = psutil.process_iter(["pid", "name", "username", "cpu_percent", "memory_percent"])
  99.     user_processes = []
  100.    
  101.     for process in processes:
  102.         process_info = process.info
  103.         if process_info["username"] != "":
  104.             user_processes.append(process_info)
  105.    
  106.     return user_processes
  107.  
  108. def get_system_uptime():
  109.     """
  110.    Get the system uptime.
  111.  
  112.    Returns:
  113.        float: System uptime in seconds.
  114.    """
  115.     return psutil.boot_time()
  116.  
  117. def press_enter_to_continue():
  118.     """
  119.    Prompt the user to press [ENTER] to continue.
  120.    """
  121.     input("Press [ENTER] to continue...\n")
  122.  
  123. def prompt_save_or_exit(data):
  124.     """
  125.    Prompt the user to save or exit the program.
  126.  
  127.    Args:
  128.        data (dict): A dictionary containing collected data.
  129.    """
  130.     print("Options:")
  131.     print("1: Save - (Or Press [ENTER])")
  132.     print("2: Exit Program")
  133.     choice = input("What is your choice (1 or 2)?\n")
  134.     if choice == '1' or choice == '':
  135.         save_data(data)
  136.     elif choice == '2':
  137.         exit()
  138.  
  139. def save_data(data):
  140.     """
  141.    Save collected data to a file.
  142.  
  143.    Args:
  144.        data (dict): A dictionary containing collected data.
  145.    """
  146.     with open('psutil_checks_output.txt', 'w') as f:
  147.         for key, value in data.items():
  148.             f.write(f"{key}:\n")
  149.             save_recursive(value, f, 4)  # Start the indentation from 4 spaces
  150.             f.write("\n")  # Add a new line after each entry
  151.     print("Data saved to 'psutil_checks_output.txt'.")
  152.  
  153. def save_recursive(data, f, indent):
  154.     """
  155.    Recursively save nested data to a file.
  156.  
  157.    Args:
  158.        data: Data to be saved.
  159.        f: File object for writing.
  160.        indent (int): Indentation level.
  161.    """
  162.     if isinstance(data, dict):
  163.         for key, value in data.items():
  164.             f.write(f"{' '*indent}{key}: ")
  165.             save_recursive(value, f, indent+4)  # Increase the indentation by 4 spaces
  166.     else:
  167.         f.write(f"{data}\n")  # Write the data with a new line
  168.            
  169. def main():
  170.     """
  171.    Main function to execute system checks.
  172.    """
  173.     # Get CPU usage
  174.     cpu_usage = get_cpu_usage()
  175.     print("CPU Usage:", cpu_usage)
  176.    
  177.     # Get system uptime
  178.     system_uptime = get_system_uptime()
  179.     print("System Uptime:", system_uptime)
  180.    
  181.     # Prompt the user to press [ENTER]
  182.     press_enter_to_continue()
  183.    
  184.     # Get system memory statistics
  185.     memory_stats = get_system_memory_statistics()
  186.     print("System Memory Statistics:", memory_stats)
  187.    
  188.     # Get disk partitions
  189.     disk_partitions = get_disk_partitions()
  190.     print("Disk Partitions:", disk_partitions)
  191.    
  192.     # Get disk usage statistics
  193.     disk_usage = get_disk_usage()
  194.     print("Disk Usage Statistics:", disk_usage)
  195.    
  196.     # Get connected users
  197.     connected_users = get_connected_users()
  198.     print("Connected Users:", connected_users)
  199.    
  200.     # Display System Utilization
  201.     press_enter_to_continue()
  202.     print("\nSystem Utilization:")
  203.     system_util = get_system_utilization()
  204.     for info, data in system_util.items():
  205.         print(f"- {info}: {data}")
  206.    
  207.     # Prompt the user to press [ENTER]
  208.     press_enter_to_continue()
  209.    
  210.     # Display Miscellaneous Information
  211.     print("\nMiscellaneous:")
  212.     misc_info = get_miscellaneous()
  213.     for info, data in misc_info.items():
  214.         print(f"- {info}: {data}")
  215.        
  216.     # Prompt the user to press [ENTER]
  217.     press_enter_to_continue()
  218.    
  219.     # Get process information
  220.     user_processes = get_process_info()
  221.     print("\nUser Processes:")
  222.     for process in user_processes:
  223.         print(f"PID: {process['pid']}, Name: {process['name']}, CPU Percent: {process['cpu_percent']}, Memory Percent: {process['memory_percent']}")
  224.    
  225.     # Prompt the user to save or exit
  226.     prompt_save_or_exit({
  227.         "CPU Usage": cpu_usage,
  228.         "System Uptime": system_uptime,
  229.         "System Memory Statistics": memory_stats,
  230.         "Disk Partitions": disk_partitions,
  231.         "Disk Usage Statistics": disk_usage,
  232.         "Connected Users": connected_users,
  233.         "System Utilization": system_util,
  234.         "Miscellaneous": misc_info,
  235.         "User Processes": user_processes
  236.     })
  237.  
  238. if __name__ == "__main__":
  239.     main()
  240.  
  241.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement