Python Tkinter菜单实现SSH连接自制NAS硬盘信息5秒自动刷新
Hey there! Glad to hear your current NAS disk monitor script is working smoothly—adding auto-refresh every 5 seconds is straightforward with Tkinter's built-in after() method, which is perfect for scheduling repeated tasks. Let me show you how to implement this cleanly, while keeping your SSH connection efficient.
Here's a refined version of your script with auto-refresh:
We'll encapsulate the logic in a class to manage the SSH connection and UI state better, and use after() to create a recurring refresh loop.
import tkinter as tk from paramiko import SSHClient, AutoAddPolicy class NASDiskMonitor: def __init__(self, root): self.root = root self.root.title("NAS Disk Space Monitor") # Set up persistent SSH connection (avoids reconnecting every 5s) self.ssh = SSHClient() self.ssh.set_missing_host_key_policy(AutoAddPolicy()) try: # Replace with your NAS credentials/IP self.ssh.connect('192.168.1.100', username='nas_user', password='your_password') except Exception as e: print(f"Failed to connect to NAS: {str(e)}") self.root.quit() # Create UI labels for disk stats self.total_cap_label = tk.Label(root, text="Total Capacity: --", font=('Arial', 12)) self.total_cap_label.pack(pady=8) self.used_space_label = tk.Label(root, text="Used Space: --", font=('Arial', 12)) self.used_space_label.pack(pady=8) self.free_space_label = tk.Label(root, text="Available Space: --", font=('Arial', 12)) self.free_space_label.pack(pady=8) # Kick off initial data load and auto-refresh loop self.refresh_disk_stats() def fetch_disk_data(self): # Adjust the df command path to match your NAS storage mount point (e.g., /mnt/storage) stdin, stdout, stderr = self.ssh.exec_command('df -h /mnt/storage | grep -v Filesystem') output = stdout.read().decode().strip() if not output: return ("N/A", "N/A", "N/A") # Parse df output (columns: Filesystem, Size, Used, Avail, Use%, Mounted on) stats = output.split() return (stats[1], stats[2], stats[3]) def refresh_disk_stats(self): total, used, free = self.fetch_disk_data() # Update UI labels with new data self.total_cap_label.config(text=f"Total Capacity: {total}") self.used_space_label.config(text=f"Used Space: {used}") self.free_space_label.config(text=f"Available Space: {free}") # Schedule next refresh in 5000ms (5 seconds) self.root.after(5000, self.refresh_disk_stats) def cleanup(self): # Ensure SSH connection closes when app exits if hasattr(self, 'ssh'): self.ssh.close() if __name__ == "__main__": root = tk.Tk() app = NASDiskMonitor(root) # Trigger cleanup when window is closed root.protocol("WM_DELETE_WINDOW", lambda: (app.cleanup(), root.destroy())) root.mainloop()
Key details to note:
- Persistent SSH Connection: We establish the SSH link once in the constructor instead of reconnecting every refresh—this is far more efficient and avoids unnecessary network overhead.
after()Loop: Therefresh_disk_statsmethod callsself.root.after(5000, self.refresh_disk_stats)at the end, telling Tkinter to rerun the function after 5 seconds. This creates a seamless auto-refresh cycle.- Clean UI Updates: We reuse the same labels and update their text with
config()instead of creating new widgets each time, which keeps the UI responsive. - Proper Cleanup: The
cleanupmethod ensures the SSH connection is closed when you close the window, preventing hanging connections.
Quick adjustments for your setup:
- Replace
192.168.1.100,nas_user, andyour_passwordwith your NAS's actual IP and credentials. - Update the
/mnt/storagepath in thedfcommand to match your NAS's storage mount point (usedf -hon your NAS to find the correct path). - If you want to handle SSH connection drops gracefully, add a try-except block inside
fetch_disk_datato attempt reconnection if the command fails.
内容的提问来源于stack exchange,提问作者alex stq
相关产品推荐
相关产品推荐

