Vigilant Data Sentry Python GUI

👤 Sharing: AI
import tkinter as tk
from tkinter import ttk
import os
import hashlib
import threading
import time
from tkinter import filedialog, messagebox

class DataSentryApp:
    def __init__(self, master):
        self.master = master
        master.title("Vigilant Data Sentry")

        self.selected_directory = tk.StringVar()
        self.hashing_algorithm = tk.StringVar(value="sha256")
        self.interval_seconds = tk.IntVar(value=60)
        self.monitoring_enabled = tk.tk.BooleanVar(value=False)
        self.stop_monitoring_event = threading.Event()

        # UI Elements
        ttk.Label(master, text="Directory to Monitor:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
        ttk.Entry(master, textvariable=self.selected_directory, width=50).grid(row=0, column=1, padx=5, pady=5, sticky="ew")
        ttk.Button(master, text="Browse", command=self.browse_directory).grid(row=0, column=2, padx=5, pady=5)

        ttk.Label(master, text="Hashing Algorithm:").grid(row=1, column=0, padx=5, pady=5, sticky="w")
        hash_combo = ttk.Combobox(master, textvariable=self.hashing_algorithm, values=["md5", "sha1", "sha256", "sha512"], state="readonly")
        hash_combo.grid(row=1, column=1, padx=5, pady=5, sticky="ew")

        ttk.Label(master, text="Monitoring Interval (seconds):").grid(row=2, column=0, padx=5, pady=5, sticky="w")
        ttk.Entry(master, textvariable=self.interval_seconds, width=10).grid(row=2, column=1, padx=5, pady=5, sticky="w")

        self.start_button = ttk.Button(master, text="Start Monitoring", command=self.start_monitoring)
        self.start_button.grid(row=3, column=0, columnspan=3, padx=5, pady=10)

        self.text_area = tk.Text(master, height=15, width=70)
        self.text_area.grid(row=4, column=0, columnspan=3, padx=5, pady=5)
        self.text_area.config(state=tk.DISABLED)

        self.detail_button = ttk.Button(master, text="Details", command=self.show_details)
        self.detail_button.grid(row=5, column=0, columnspan=3, padx=5, pady=10)

        master.grid_columnconfigure(1, weight=1)  # Make the entry field expandable

    def browse_directory(self):
        directory = filedialog.askdirectory()
        if directory:
            self.selected_directory.set(directory)

    def start_monitoring(self):
        if not self.selected_directory.get():
            messagebox.showerror("Error", "Please select a directory to monitor.")
            return
        try:
            interval = int(self.interval_seconds.get())
            if interval <= 0:
                raise ValueError
        except ValueError:
            messagebox.showerror("Error", "Invalid monitoring interval.  Must be a positive integer.")
            return

        if not self.monitoring_enabled.get():
            self.monitoring_enabled.set(True)
            self.start_button.config(text="Stop Monitoring")
            self.stop_monitoring_event.clear()
            threading.Thread(target=self.monitor_directory, daemon=True).start()
        else:
            self.monitoring_enabled.set(False)
            self.start_button.config(text="Start Monitoring")
            self.stop_monitoring_event.set()

    def monitor_directory(self):
        directory = self.selected_directory.get()
        hashing_algorithm = self.hashing_algorithm.get()
        interval = int(self.interval_seconds.get())

        previous_hashes = self.calculate_directory_hashes(directory, hashing_algorithm)

        while self.monitoring_enabled.get():
            time.sleep(interval)
            if self.stop_monitoring_event.is_set():
                break

            current_hashes = self.calculate_directory_hashes(directory, hashing_algorithm)
            changes = self.compare_hashes(previous_hashes, current_hashes)

            if changes:
                self.update_text_area(changes)
            previous_hashes = current_hashes

    def calculate_directory_hashes(self, directory, hashing_algorithm):
        hashes = {}
        for root, _, files in os.walk(directory):
            for file in files:
                filepath = os.path.join(root, file)
                try:
                    with open(filepath, "rb") as f:
                        file_content = f.read()
                        if hashing_algorithm == "md5":
                            hash_object = hashlib.md5(file_content)
                        elif hashing_algorithm == "sha1":
                            hash_object = hashlib.sha1(file_content)
                        elif hashing_algorithm == "sha256":
                            hash_object = hashlib.sha256(file_content)
                        elif hashing_algorithm == "sha512":
                            hash_object = hashlib.sha512(file_content)
                        else:
                            raise ValueError("Invalid hashing algorithm")
                        hashes[filepath] = hash_object.hexdigest()
                except Exception as e:
                    self.update_text_area(f"Error processing {filepath}: {e}\n")

        return hashes

    def compare_hashes(self, previous_hashes, current_hashes):
        changes = []

        # Check for new files or modified files
        for filepath, current_hash in current_hashes.items():
            if filepath not in previous_hashes:
                changes.append(f"New file detected: {filepath}")
            elif current_hash != previous_hashes[filepath]:
                changes.append(f"File modified: {filepath}")

        # Check for deleted files
        for filepath in previous_hashes:
            if filepath not in current_hashes:
                changes.append(f"File deleted: {filepath}")

        return changes

    def update_text_area(self, changes):
        self.text_area.config(state=tk.NORMAL)
        for change in changes:
            self.text_area.insert(tk.END, change + "\n")
        self.text_area.config(state=tk.DISABLED)
        self.text_area.see(tk.END)

    def show_details(self):
       details_text = """Vigilant Data Sentry: Real-time File Integrity Monitoring

        This application provides continuous monitoring of a specified directory, detecting changes to files, including modifications, additions, and deletions.

        Key Features:
        - Real-time monitoring: Scans the directory at user-defined intervals.
        - Multiple hashing algorithms: Supports MD5, SHA1, SHA256, and SHA512 for robust integrity checks.
        - Detailed change log:  Records all detected file changes.
        - User-friendly GUI: Easy to configure and use.
        - Threaded operation: Monitoring runs in the background, preventing UI freezes.

        Use Cases:
        - Security auditing: Detect unauthorized file modifications.
        - Data loss prevention: Identify accidental or malicious file deletions.
        - System monitoring: Track changes to critical system files.
        - Compliance: Meet regulatory requirements for data integrity.

        Algorithm Highlights:
        - Directory Hashing: Calculates cryptographic hashes of all files within the monitored directory.  The chosen hashing algorithm determines the sensitivity and computational cost of the monitoring.
        - Change Detection: Compares the current file hashes with the previous hashes to identify differences.  This ensures that even small changes to a file are detected.

        This tool provides a vital layer of security for your data by quickly identifying and reporting any unauthorized changes.
        """
       messagebox.showinfo("Details", details_text)

root = tk.Tk()
app = DataSentryApp(root)
root.mainloop()
👁️ Viewed: 5

Comments