You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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: The refresh_disk_stats method calls self.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 cleanup method ensures the SSH connection is closed when you close the window, preventing hanging connections.

Quick adjustments for your setup:

  1. Replace 192.168.1.100, nas_user, and your_password with your NAS's actual IP and credentials.
  2. Update the /mnt/storage path in the df command to match your NAS's storage mount point (use df -h on your NAS to find the correct path).
  3. If you want to handle SSH connection drops gracefully, add a try-except block inside fetch_disk_data to attempt reconnection if the command fails.

内容的提问来源于stack exchange,提问作者alex stq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:15:00