diff --git a/#1754_DISK_SPACE_ALERT_SYSTEM/README.md b/#1754_DISK_SPACE_ALERT_SYSTEM/README.md new file mode 100644 index 0000000..f71ebd9 --- /dev/null +++ b/#1754_DISK_SPACE_ALERT_SYSTEM/README.md @@ -0,0 +1,39 @@ +# Disk Space Alert System + +A simple, cross-platform Python script that monitors disk space on all connected drives and sends a native desktop notification if any drive's usage exceeds a set threshold. + +## Features + +- **Monitors All Drives:** Automatically discovers and checks all physical disk partitions (e.g., C:\, D:\ on Windows; / , /home on Linux). +- **Desktop Alerts:** Uses `plyer` to send native desktop notifications on Windows, macOS, and Linux. +- **Logging:** Logs all checks and alerts to a `disk_monitor.log` file for review. +- **Configurable:** Easily set the usage threshold and check frequency. +- **Lightweight:** Runs in the background with minimal resource usage. + +## Requirements + +- Python 3.x +- `psutil` library +- `plyer` library + +## Installation + +1. **Clone or download** this repository (or just save `disk_monitor.py`). + +2. **Install the required Python libraries** using pip: + ```bash + pip install psutil plyer + ``` + +## Configuration + +Open the `disk_monitor.py` file in a text editor and modify the configuration section at the top: + +```python +# --- Configuration --- +# Set the disk usage percentage threshold (e.g., 80%) +THRESHOLD_PERCENT = 80 + +# How often to check (in seconds) +CHECK_INTERVAL_SECONDS = 600 # 10 minutes +# --------------------- \ No newline at end of file diff --git a/#1754_DISK_SPACE_ALERT_SYSTEM/alert.py b/#1754_DISK_SPACE_ALERT_SYSTEM/alert.py new file mode 100644 index 0000000..6832d84 --- /dev/null +++ b/#1754_DISK_SPACE_ALERT_SYSTEM/alert.py @@ -0,0 +1,82 @@ +import psutil +import time +import logging +from plyer import notification +import os + +# --- Configuration --- +# Set the disk usage percentage threshold (e.g., 80%) +THRESHOLD_PERCENT = 80 + +# How often to check (in seconds) +CHECK_INTERVAL_SECONDS = 600 # 10 minutes +# --------------------- + +# Configure logging +logging.basicConfig(level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[logging.FileHandler("disk_monitor.log"), + logging.StreamHandler()]) + +def send_notification(title, message): + """Sends a desktop notification and logs the alert.""" + logging.warning(message) # Log as a warning since it's an alert + try: + notification.notify( + title=title, + message=message, + app_name='Disk Monitor', + timeout=10 # Notification will stay for 10 seconds + ) + except Exception as e: + logging.error(f"Failed to send desktop notification: {e}") + +def check_all_disks(): + """ + Checks usage for all physical disk partitions and sends alerts + if any exceed the threshold. + """ + logging.info("Starting disk usage check...") + + # Get all mounted disk partitions + try: + partitions = psutil.disk_partitions() + except Exception as e: + logging.error(f"Failed to get disk partitions: {e}") + return + + for partition in partitions: + # On Windows, psutil.disk_partitions() can return drives that + # aren't ready (e.g., empty CD-ROM). We'll try to get usage + # and skip if it fails. + # On Linux/macOS, this skips 'squashfs' and other special types. + try: + usage = psutil.disk_usage(partition.mountpoint) + + current_usage_percent = usage.percent + + log_msg = (f"Checking '{partition.device}' ({partition.mountpoint}) " + f"- Usage: {current_usage_percent}%") + logging.info(log_msg) + + # Check if usage exceeds the threshold + if current_usage_percent > THRESHOLD_PERCENT: + title = "⚠️ Disk Space Alert" + message = ( + f"Partition '{partition.mountpoint}' is running low on space! " + f"Current: {current_usage_percent}% | Threshold: {THRESHOLD_PERCENT}%" + ) + send_notification(title, message) + + except (PermissionError, FileNotFoundError, OSError) as e: + # Log and skip partitions that can't be read (e.g., empty CD-ROM) + logging.warning(f"Could not read disk '{partition.device}': {e}") + except Exception as e: + logging.error(f"An unexpected error occurred for '{partition.device}': {e}") + +if __name__ == "__main__": + logging.info("Starting Disk Monitor Service...") + while True: + check_all_disks() + logging.info(f"Check complete. Next check in {CHECK_INTERVAL_SECONDS} seconds.") + time.sleep(CHECK_INTERVAL_SECONDS) diff --git a/#1762_USB_DEVICE_DETECT/README.md b/#1762_USB_DEVICE_DETECT/README.md new file mode 100644 index 0000000..21afe80 --- /dev/null +++ b/#1762_USB_DEVICE_DETECT/README.md @@ -0,0 +1,49 @@ +# USB Device Detector + +This script detects and logs when USB devices are plugged in or removed from the system. + +It is cross-platform and supports two different detection methods: +* **Linux:** Uses `pyudev` for real-time, event-based monitoring. +* **Windows:** Uses `WMI` to poll for changes in connected Plug-and-Play (PnP) devices. + +All events are logged to the console and to a file named `usb_detector.log`. + +## Requirements + +- Python 3.x +- Platform-specific libraries (see below) + +## Installation + +1. **Clone or download** this repository (or just save `usb_detector.py`). + +2. **Install the required Python library** based on your operating system: + + * **On Linux:** + ```bash + pip install pyudev + ``` + * **On Windows:** + ```bash + pip install WMI + ``` + +## Usage + +You must run the script with elevated privileges to allow it to monitor system hardware. + +* **On Linux:** + Run the script with `sudo`. + ```bash + sudo python3 usb_detector.py + ``` + +* **On Windows:** + Run your terminal (Command Prompt or PowerShell) as **Administrator**, then run the script. + ```bash + python usb_detector.py + ``` + +### Log Output + +The script will create a `usb_detector.log` file in the same directory. Output will look similar to this: \ No newline at end of file diff --git a/#1762_USB_DEVICE_DETECT/usb_detect.py b/#1762_USB_DEVICE_DETECT/usb_detect.py new file mode 100644 index 0000000..6558486 --- /dev/null +++ b/#1762_USB_DEVICE_DETECT/usb_detect.py @@ -0,0 +1,98 @@ +import platform +import time +import logging +try: + # For Linux + import pyudev + LINUX_READY = True +except ImportError: + LINUX_READY = False +try: + # For Windows + import wmi + WINDOWS_READY = True +except ImportError: + WINDOWS_READY = False +# ----------------------------------- +# --- Configuration --- +# How often to check for changes (in seconds) on Windows. +# Linux uses real-time events, so this is ignored. +POLL_INTERVAL_SECONDS = 2 +# --------------------- +logging.basicConfig(level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[logging.FileHandler("usb_detector.log"), + logging.StreamHandler()]) + +def monitor_linux(): + """Uses pyudev to listen for real-time USB events on Linux.""" + logging.info("Starting Linux USB monitor (using pyudev)...") + context = pyudev.Context() + monitor = pyudev.Monitor.from_netlink(context) + monitor.filter_by(subsystem='usb') + + logging.info("Monitor started. Waiting for events...") + for device in iter(monitor.poll, None): + if device.action == 'add': + logging.info(f"USB Device ADDED: {device.get('ID_MODEL', 'Unknown')} (Vendor: {device.get('ID_VENDOR_ID', 'N/A')})") + elif device.action == 'remove': + logging.info(f"USB Device REMOVED: {device.get('ID_MODEL', 'Unknown')} (Vendor: {device.get('ID_VENDOR_ID', 'N/A')})") + +def monitor_windows(): + """Uses WMI to poll for USB device changes on Windows.""" + logging.info(f"Starting Windows USB monitor (polling every {POLL_INTERVAL_SECONDS}s)...") + c = wmi.WMI() + + # Get initial set of USB PnP devices + initial_devices_map = {d.DeviceID: d.Name for d in c.Win32_PnPEntity() if "USB" in (d.Description or "")} + while True: + try: + # Get current set of devices + current_devices_map = {d.DeviceID: d.Name for d in c.Win32_PnPEntity() if "USB" in (d.Description or "")} + + current_ids = set(current_devices_map.keys()) + initial_ids = set(initial_devices_map.keys()) + + # Check for added devices + added_ids = current_ids - initial_ids + if added_ids: + for dev_id in added_ids: + logging.info(f"USB Device ADDED: {current_devices_map[dev_id]} (ID: {dev_id})") + + # Check for removed devices + removed_ids = initial_ids - current_ids + if removed_ids: + for dev_id in removed_ids: + logging.info(f"USB Device REMOVED: {initial_devices_map[dev_id]} (ID: {dev_id})") + + # Update the initial state + initial_devices_map = current_devices_map + + except Exception as e: + logging.error(f"Error during WMI poll: {e}") + + time.sleep(POLL_INTERVAL_SECONDS) +if __name__ == "__main__": + system = platform.system() + + if system == "Linux": + if not LINUX_READY: + logging.error("Linux detected, but 'pyudev' library is not installed.") + logging.error("Please run: pip install pyudev") + else: + logging.info("Linux detected. Requires 'sudo' to run.") + try: + monitor_linux() + except Exception as e: + logging.critical(f"Failed to run Linux monitor. Did you run with 'sudo'? Error: {e}") + + elif system == "Windows": + if not WINDOWS_READY: + logging.error("Windows detected, but 'WMI' library is not installed.") + logging.error("Please run: pip install WMI") + else: + logging.info("Windows detected. May require 'Administrator' privileges.") + monitor_windows() + + else: + logging.warning(f"Unsupported platform: {system}. This script only supports Linux and Windows.") \ No newline at end of file