如何写一个脚本检查文件是否被锁

wen 实用脚本 1

本文目录导读:

如何写一个脚本检查文件是否被锁

  1. Linux/Unix 系统脚本
  2. Python 脚本
  3. Windows PowerShell 脚本
  4. Shell 函数(可直接在shell中使用)
  5. 使用示例
  6. 注意事项

Linux/Unix 系统脚本

使用 lsof 命令

#!/bin/bash
# 检查文件是否被锁
file_path="$1"
if [ -z "$file_path" ]; then
    echo "用法: $0 <文件路径>"
    exit 1
fi
if [ ! -f "$file_path" ]; then
    echo "文件不存在: $file_path"
    exit 1
fi
# 使用lsof检查文件是否被打开
if lsof "$file_path" > /dev/null 2>&1; then
    echo "文件被锁定: $file_path"
    echo "持有锁的进程:"
    lsof "$file_path"
else
    echo "文件未被锁定: $file_path"
fi

使用 flock 测试

#!/bin/bash
file_path="$1"
if [ -z "$file_path" ]; then
    echo "用法: $0 <文件路径>"
    exit 1
fi
# 尝试获取排他锁
(
    if flock -n 200 2>/dev/null; then
        echo "文件未被锁定"
        exit 0
    else
        echo "文件已被锁定"
        exit 1
    fi
) 200>"$file_path"

Python 脚本

#!/usr/bin/env python3
import os
import sys
import fcntl
import subprocess
def check_file_lock(file_path):
    """检查文件是否被锁"""
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        return False
    try:
        # 方法1: 使用fcntl尝试获取锁
        with open(file_path, 'r') as f:
            try:
                fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
                fcntl.flock(f, fcntl.LOCK_UN)
                print("文件未被锁定 (fcntl检测)")
                return False
            except IOError:
                print("文件已被锁定 (fcntl检测)")
                return True
    except Exception as e:
        print(f"检测失败: {e}")
        return False
def check_with_lsof(file_path):
    """使用lsof命令检查"""
    try:
        result = subprocess.run(
            ['lsof', file_path], 
            capture_output=True, 
            text=True
        )
        if result.returncode == 0:
            print(f"文件被锁定,持有进程:")
            print(result.stdout)
            return True
        else:
            print("文件未被锁定")
            return False
    except Exception as e:
        print(f"lsof检测失败: {e}")
        return False
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(f"用法: {sys.argv[0]} <文件路径>")
        sys.exit(1)
    file_path = sys.argv[1]
    # 同时使用两种方法
    is_locked_fcntl = check_file_lock(file_path)
    is_locked_lsof = check_with_lsof(file_path)
    if is_locked_fcntl or is_locked_lsof:
        sys.exit(1)  # 文件被锁
    else:
        sys.exit(0)  # 文件未被锁

Windows PowerShell 脚本

param(
    [Parameter(Mandatory=$true)]
    [string]$FilePath
)
function Check-FileLock {
    param(
        [string]$FilePath
    )
    if (-not (Test-Path $FilePath)) {
        Write-Host "文件不存在: $FilePath" -ForegroundColor Red
        return $false
    }
    try {
        # 尝试以独占方式打开文件
        $file = [System.IO.File]::Open($FilePath, 
            [System.IO.FileMode]::Open, 
            [System.IO.FileAccess]::Read, 
            [System.IO.FileShare]::None)
        $file.Close()
        Write-Host "文件未被锁定" -ForegroundColor Green
        return $false
    }
    catch [System.IO.IOException] {
        Write-Host "文件已被锁定" -ForegroundColor Red
        return $true
    }
    catch {
        Write-Host "检测失败: $_" -ForegroundColor Red
        return $null
    }
}
# 执行检查
$isLocked = Check-FileLock -FilePath $FilePath
if ($isLocked) {
    # 可选:显示锁定进程
    try {
        $lockedProcess = Get-Process | Where-Object {
            $_.Modules.FileName -eq $FilePath
        }
        if ($lockedProcess) {
            Write-Host "锁定进程: $($lockedProcess.Name) (PID: $($lockedProcess.Id))" -ForegroundColor Yellow
        }
    }
    catch {}
}
exit ($isLocked ? 1 : 0)

Shell 函数(可直接在shell中使用)

# 添加到 .bashrc 或 .zshrc
check_lock() {
    local file="$1"
    if [ ! -f "$file" ]; then
        echo "文件不存在: $file"
        return 2
    fi
    if lsof "$file" 2>/dev/null | grep -q "$file"; then
        echo "文件被锁定"
        lsof "$file"
        return 0
    else
        echo "文件未被锁定"
        return 1
    fi
}
# 使用方式
# check_lock /path/to/file

使用示例

# 测试脚本
./check_lock.sh /var/log/syslog
python3 check_lock.py /etc/passwd
powershell -File check_lock.ps1 -FilePath "C:\test.txt"

注意事项

  1. 权限问题:某些文件可能需要root权限才能检查
  2. 性能影响:频繁检查可能影响系统性能
  3. 竞争条件:检查结果可能瞬间变化
  4. 文件系统支持:某些文件系统可能不支持锁检测

选择哪种方法取决于你的操作系统和具体需求。

抱歉,评论功能暂时关闭!