Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: psutil_checks.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- This script performs various system checks using the psutil library and saves the collected data to a file.
- """
- import psutil
- def get_cpu_usage():
- """
- Get the current CPU usage percentage.
- Returns:
- float: The CPU usage percentage.
- """
- return psutil.cpu_percent(interval=1)
- def get_system_memory_statistics():
- """
- Get the system memory statistics.
- Returns:
- dict: A dictionary containing system memory statistics.
- """
- return psutil.virtual_memory()
- def get_disk_partitions():
- """
- Get the disk partitions.
- Returns:
- list: A list of disk partitions.
- """
- return psutil.disk_partitions()
- def get_disk_usage(partition='/'):
- """
- Get the disk usage statistics.
- Args:
- partition (str): The disk partition to check. Default is '/'.
- Returns:
- tuple: A tuple containing disk usage statistics.
- """
- return psutil.disk_usage(partition)
- def get_connected_users():
- """
- Get information about currently connected users.
- Returns:
- list: A list of connected users.
- """
- return psutil.users()
- def get_system_utilization():
- """
- Get various system utilization metrics.
- Returns:
- dict: A dictionary containing system utilization metrics.
- """
- system_util = {
- "CPU Times Percent": psutil.cpu_times_percent(),
- "Logical CPU Count": psutil.cpu_count(),
- "CPU Frequency": psutil.cpu_freq(),
- "Network I/O Statistics": psutil.net_io_counters(),
- "Network Connections": psutil.net_connections(),
- "System Boot Time": psutil.boot_time()
- }
- return system_util
- def get_miscellaneous():
- """
- Get miscellaneous system information.
- Returns:
- dict: A dictionary containing miscellaneous system information.
- """
- test_suite_result = psutil.test()
- misc_info = {}
- if test_suite_result is not None:
- misc_info["psutil Test Suite"] = test_suite_result
- return misc_info
- def get_process_info():
- """
- Get information about running processes.
- Returns:
- list: A list of dictionaries containing process information.
- """
- processes = psutil.process_iter(["pid", "name", "username", "cpu_percent", "memory_percent"])
- user_processes = []
- for process in processes:
- process_info = process.info
- if process_info["username"] != "":
- user_processes.append(process_info)
- return user_processes
- def get_system_uptime():
- """
- Get the system uptime.
- Returns:
- float: System uptime in seconds.
- """
- return psutil.boot_time()
- def press_enter_to_continue():
- """
- Prompt the user to press [ENTER] to continue.
- """
- input("Press [ENTER] to continue...\n")
- def prompt_save_or_exit(data):
- """
- Prompt the user to save or exit the program.
- Args:
- data (dict): A dictionary containing collected data.
- """
- print("Options:")
- print("1: Save - (Or Press [ENTER])")
- print("2: Exit Program")
- choice = input("What is your choice (1 or 2)?\n")
- if choice == '1' or choice == '':
- save_data(data)
- elif choice == '2':
- exit()
- def save_data(data):
- """
- Save collected data to a file.
- Args:
- data (dict): A dictionary containing collected data.
- """
- with open('psutil_checks_output.txt', 'w') as f:
- for key, value in data.items():
- f.write(f"{key}:\n")
- save_recursive(value, f, 4) # Start the indentation from 4 spaces
- f.write("\n") # Add a new line after each entry
- print("Data saved to 'psutil_checks_output.txt'.")
- def save_recursive(data, f, indent):
- """
- Recursively save nested data to a file.
- Args:
- data: Data to be saved.
- f: File object for writing.
- indent (int): Indentation level.
- """
- if isinstance(data, dict):
- for key, value in data.items():
- f.write(f"{' '*indent}{key}: ")
- save_recursive(value, f, indent+4) # Increase the indentation by 4 spaces
- else:
- f.write(f"{data}\n") # Write the data with a new line
- def main():
- """
- Main function to execute system checks.
- """
- # Get CPU usage
- cpu_usage = get_cpu_usage()
- print("CPU Usage:", cpu_usage)
- # Get system uptime
- system_uptime = get_system_uptime()
- print("System Uptime:", system_uptime)
- # Prompt the user to press [ENTER]
- press_enter_to_continue()
- # Get system memory statistics
- memory_stats = get_system_memory_statistics()
- print("System Memory Statistics:", memory_stats)
- # Get disk partitions
- disk_partitions = get_disk_partitions()
- print("Disk Partitions:", disk_partitions)
- # Get disk usage statistics
- disk_usage = get_disk_usage()
- print("Disk Usage Statistics:", disk_usage)
- # Get connected users
- connected_users = get_connected_users()
- print("Connected Users:", connected_users)
- # Display System Utilization
- press_enter_to_continue()
- print("\nSystem Utilization:")
- system_util = get_system_utilization()
- for info, data in system_util.items():
- print(f"- {info}: {data}")
- # Prompt the user to press [ENTER]
- press_enter_to_continue()
- # Display Miscellaneous Information
- print("\nMiscellaneous:")
- misc_info = get_miscellaneous()
- for info, data in misc_info.items():
- print(f"- {info}: {data}")
- # Prompt the user to press [ENTER]
- press_enter_to_continue()
- # Get process information
- user_processes = get_process_info()
- print("\nUser Processes:")
- for process in user_processes:
- print(f"PID: {process['pid']}, Name: {process['name']}, CPU Percent: {process['cpu_percent']}, Memory Percent: {process['memory_percent']}")
- # Prompt the user to save or exit
- prompt_save_or_exit({
- "CPU Usage": cpu_usage,
- "System Uptime": system_uptime,
- "System Memory Statistics": memory_stats,
- "Disk Partitions": disk_partitions,
- "Disk Usage Statistics": disk_usage,
- "Connected Users": connected_users,
- "System Utilization": system_util,
- "Miscellaneous": misc_info,
- "User Processes": user_processes
- })
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement