如何用Ansible检测Linux(Ubuntu16.04)文件系统是否为只读?
我完全理解你的痛点——用创建测试文件的方法不仅繁琐还带侵入性,而且stat确实只能拿到POSIX权限,没法反映文件系统实际的挂载状态。下面分享几个更优雅的非侵入式方案,既能检测读写模式,还能判断目标目录是不是挂载点:
方法1:使用findmnt命令(推荐,最简洁)
findmnt是systemd工具集里的专用挂载信息查询工具,Ubuntu 16.04默认已预装,输出结果清晰易解析。
检测文件系统读写状态
替换/your/target/dir为你要检测的目录,执行:
findmnt -no OPTIONS --target /your/target/dir
- 输出包含
rw:文件系统处于读写模式 - 输出包含
ro:文件系统处于只读模式
判断是否为挂载点
执行:
findmnt -no TARGET --target /your/target/dir
如果输出路径和你输入的目标目录完全一致,说明该目录就是挂载点;如果输出是上级路径,则它属于某个挂载点下的子目录。
方法2:解析/proc/mounts文件
/proc/mounts是内核维护的挂载信息源文件,内容直接可靠,无需依赖额外工具。
可以用Shell脚本组合解析:
target_dir="/your/target/dir" # 获取目标目录所在的挂载点 mount_point=$(df -P "$target_dir" | tail -1 | awk '{print $6}') # 查询该挂载点的挂载选项 mount_options=$(awk -v mp="$mount_point" '$2 == mp {print $4}' /proc/mounts) # 判断读写状态 if [[ "$mount_options" == *ro* ]]; then echo "$mount_point 处于只读模式" else echo "$mount_point 处于读写模式" fi # 判断目标目录是否为挂载点 if [[ "$mount_point" == "$target_dir" ]]; then echo "$target_dir 是挂载点" else echo "$target_dir 不是挂载点" fi
方法3:Python非侵入式实现
如果你需要用Python代码完成需求,这里提供两种思路:
解析/proc/mounts的纯Python方案
无需调用外部命令,直接读取系统文件:
from pathlib import Path import os def check_filesystem_status(target_path): target = Path(target_path).resolve() # 向上遍历找到最近的挂载点 mount_point = target while not os.path.ismount(mount_point): mount_point = mount_point.parent if mount_point == Path('/'): break # 读取/proc/mounts解析挂载选项 with open('/proc/mounts', 'r') as f: for line in f: parts = line.strip().split() mp = Path(parts[1]) if mp == mount_point: options = parts[3].split(',') return { 'mount_point': str(mount_point), 'is_readonly': 'ro' in options, 'is_mountpoint': target == mount_point } return None # 使用示例 result = check_filesystem_status('/your/target/dir') if result: print(f"挂载点: {result['mount_point']}") print(f"是否只读: {'是' if result['is_readonly'] else '否'}") print(f"目标目录是否为挂载点: {'是' if result['is_mountpoint'] else '否'}") else: print("无法获取文件系统信息")
调用findmnt的Python方案
借助系统工具简化代码逻辑:
import subprocess def check_filesystem_status(target_path): try: # 获取挂载选项 options = subprocess.check_output( ['findmnt', '-no', 'OPTIONS', '--target', target_path], text=True ).strip() is_readonly = 'ro' in options.split(',') # 获取对应的挂载点 mount_point = subprocess.check_output( ['findmnt', '-no', 'TARGET', '--target', target_path], text=True ).strip() is_mountpoint = mount_point == target_path return { 'mount_point': mount_point, 'is_readonly': is_readonly, 'is_mountpoint': is_mountpoint } except subprocess.CalledProcessError: return None # 使用示例 result = check_filesystem_status('/your/target/dir') if result: print(f"挂载点: {result['mount_point']}") print(f"是否只读: {'是' if result['is_readonly'] else '否'}") print(f"目标目录是否为挂载点: {'是' if result['is_mountpoint'] else '否'}") else: print("无法获取文件系统信息")
这些方案都是直接读取系统的挂载元数据,完全不需要创建任何测试文件,准确反映文件系统的实际读写能力,同时也能轻松判断挂载点属性。
内容的提问来源于stack exchange,提问作者Isac Casapu
相关产品推荐
相关产品推荐

