You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用Python脚本对比du与df输出,检查vApp中ISO挂载状态?

Checking if an ISO is Unmounted: Comparing df/du and Better Alternatives

Great question—your idea to compare df and du outputs is a clever way to infer mount status, but there are more direct, reliable methods, and we can refine your original approach to avoid edge cases. Let’s break this down.

Refining the df vs du Approach

First, a key adjustment: use du -x to exclude mounted filesystems. Without the -x flag, du will traverse the mounted ISO’s files if it’s still attached, which defeats the purpose of the comparison. Here’s how it works:

  • df -hk /mountpoint reports the total/used size of the filesystem currently attached to that path.
  • du -xsch /mountpoint calculates the size of the underlying directory (ignoring any mounted filesystems at that path).

If the ISO is still mounted, df will show the ISO’s filesystem size, while du -x will show the original directory’s size (likely much smaller). If unmounted, both commands will reflect the same filesystem’s usage.

Here’s how to implement this in Python:

import subprocess

def get_df_used_size(mount_point):
    """Get used size (KB) from df for the mount point"""
    try:
        result = subprocess.run(
            ['df', '-hk', mount_point],
            capture_output=True,
            text=True,
            check=True
        )
        # Split output lines; second line contains data
        data_line = result.stdout.strip().split('\n')[1]
        # Third column is used size (KB)
        return int(data_line.split()[2])
    except (subprocess.CalledProcessError, IndexError):
        return None

def get_du_underlying_size(mount_point):
    """Get size (KB) of the underlying directory (ignoring mounts)"""
    try:
        result = subprocess.run(
            ['du', '-xsch', mount_point],
            capture_output=True,
            text=True,
            check=True
        )
        # Last line is total size
        total_line = result.stdout.strip().split('\n')[-1]
        return int(total_line.split()[0])
    except (subprocess.CalledProcessError, IndexError):
        return None

# Example usage
mount_dir = '/path/to/your/mountpoint'
df_size = get_df_used_size(mount_dir)
du_size = get_du_underlying_size(mount_dir)

if df_size and du_size:
    # Allow small threshold for filesystem overhead
    if abs(df_size - du_size) > 100:
        print("ISO is likely still mounted")
    else:
        print("ISO appears to be unmounted")
else:
    print("Failed to retrieve size data")

Note: Adjust the threshold (100 KB) based on your expected filesystem overhead to avoid false positives.

More Reliable Direct Methods

The df/du approach is indirect and can have edge cases (e.g., if the ISO size matches the original directory size). For better reliability, use these direct checks:

1. Use the mountpoint Command

This tool is purpose-built to check if a path is a mount point. It returns an exit code of 0 if mounted, 1 otherwise.

import subprocess

def is_mounted(mount_point):
    try:
        # -q suppresses output, just checks exit code
        subprocess.run(['mountpoint', '-q', mount_point], check=True)
        return True
    except subprocess.CalledProcessError:
        return False

if is_mounted('/path/to/your/mountpoint'):
    print("ISO is still mounted")
else:
    print("ISO is unmounted")

2. Parse /proc/mounts

This file lists all currently mounted filesystems. It’s portable across all Linux systems (no extra tools needed).

def is_mounted(mount_point):
    with open('/proc/mounts', 'r') as f:
        for line in f:
            # Split line into parts; second part is the mount point
            parts = line.strip().split()
            if len(parts) >= 2 and parts[1] == mount_point:
                return True
    return False

if is_mounted('/path/to/your/mountpoint'):
    print("ISO is still mounted")
else:
    print("ISO is unmounted")

Recommendation

For most cases, using mountpoint or parsing /proc/mounts is better—they’re faster, more accurate, and avoid the ambiguity of size comparisons. Stick with df/du only if you need to verify both mount status and filesystem consistency.

内容的提问来源于stack exchange,提问作者Stephen Dunne

火山引擎 最新活动