用脚本实现文件使用记录行吗

wen 实用脚本 2

本文目录导读:

用脚本实现文件使用记录行吗

  1. Linux 文件访问监控脚本
  2. Python 跨平台文件监控脚本
  3. 极简版监控脚本(无第三方库)
  4. 安装依赖
  5. 运行方法
  6. 输出示例
  7. 使用建议

当然可以!我来为您提供一个文件使用记录监控脚本,这里提供几个不同平台的实现方案:

Linux 文件访问监控脚本

#!/bin/bash
# 文件访问监控脚本 (Linux)
# 配置
LOG_FILE="/var/log/file_access.log"
MONITOR_DIR="/path/to/your/directory"  # 要监控的目录
WATCH_INTERVAL=5  # 检查间隔(秒)
# 创建日志文件
touch "$LOG_FILE"
# 使用 inotifywait 监控文件访问
echo "开始监控 $MONITOR_DIR ..."
inotifywait -m -r --format '%T %w%f %e' \
    --timefmt '%Y-%m-%d %H:%M:%S' \
    "$MONITOR_DIR" | while read timestamp file event
do
    echo "$timestamp | $event | $file" >> "$LOG_FILE"
done

Python 跨平台文件监控脚本

#!/usr/bin/env python3
# 文件使用记录监控脚本(跨平台)
import os
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import json
from datetime import datetime
class FileMonitorHandler(FileSystemEventHandler):
    def __init__(self, log_file):
        self.log_file = log_file
        self.setup_logging()
    def setup_logging(self):
        logging.basicConfig(
            filename=self.log_file,
            level=logging.INFO,
            format='%(asctime)s | %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
    def log_event(self, event_type, src_path, dest_path=None):
        log_data = {
            "timestamp": datetime.now().isoformat(),
            "event": event_type,
            "source": src_path,
            "destination": dest_path or ""
        }
        logging.info(json.dumps(log_data))
        # 同时输出到控制台
        print(f"[{log_data['timestamp']}] {event_type}: {src_path}")
    def on_created(self, event):
        if not event.is_directory:
            self.log_event("CREATED", event.src_path)
    def on_modified(self, event):
        if not event.is_directory:
            self.log_event("MODIFIED", event.src_path)
    def on_deleted(self, event):
        if not event.is_directory:
            self.log_event("DELETED", event.src_path)
    def on_moved(self, event):
        if not event.is_directory:
            self.log_event("MOVED", event.src_path, event.dest_path)
def main():
    # 配置
    MONITOR_PATH = r"C:\Users\YourUsername\Documents"  # Windows示例
    # MONITOR_PATH = "/home/username/Documents"  # Linux示例
    LOG_FILE = "file_usage.log"  # 日志文件路径
    if not os.path.exists(MONITOR_PATH):
        print(f"错误: 路径 {MONITOR_PATH} 不存在")
        return
    print(f"开始监控目录: {MONITOR_PATH}")
    print(f"日志文件: {LOG_FILE}")
    print("按 Ctrl+C 停止监控...")
    event_handler = FileMonitorHandler(LOG_FILE)
    observer = Observer()
    observer.schedule(event_handler, MONITOR_PATH, recursive=True)  # recursive=True 递归监控子目录
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        print("\n监控已停止")
    observer.join()
if __name__ == "__main__":
    main()

极简版监控脚本(无第三方库)

#!/usr/bin/env python3
# 简易文件监控(使用系统命令)
import os
import subprocess
import time
from datetime import datetime
def monitor_windows():
    """Windows 下的文件监控"""
    path = r"C:\Your\Directory"
    cmd = f'powershell -Command "Get-ChildItem -Path {path} -Recurse | Select-Object Name,LastWriteTime"'
    while True:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with open("file_log.txt", "a", encoding="utf-8") as f:
            f.write(f"\n=== {timestamp} ===\n")
            f.write(result.stdout)
        time.sleep(10)
def monitor_linux():
    """Linux 下的文件监控"""
    path = "/var/log/your_dir"
    while True:
        result = subprocess.run(['ls', '-la', path], capture_output=True, text=True)
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with open("file_log.txt", "a", encoding="utf-8") as f:
            f.write(f"\n=== {timestamp} ===\n")
            f.write(result.stdout)
        time.sleep(10)
# 根据操作系统选择
if os.name == 'nt':  # Windows
    monitor_windows()
else:  # Linux
    monitor_linux()

安装依赖

Python 版本需要安装 watchdog:

pip install watchdog

运行方法

Linux 脚本:

chmod +x monitor.sh
./monitor.sh

Python 脚本:

# 直接运行
python3 file_monitor.py
# 后台运行
nohup python3 file_monitor.py > monitor.log 2>&1 &

输出示例

2024-01-15 10:30:25 | MODIFIED: C:\Users\test\Documents\report.pdf
2024-01-15 10:31:02 | CREATED: C:\Users\test\Documents\new_file.txt
2024-01-15 10:32:18 | MOVED: C:\Users\test\Documents\old.txt to C:\Users\test\Documents\new.txt

使用建议

  1. 选择合适的位置:不要监控整个系统盘,只监控需要的目录
  2. 日志管理:定期清理日志文件,避免占满磁盘
  3. 性能考虑:监控大文件或高频率访问的文件可能会影响性能
  4. 权限设置:确保脚本有足够的权限访问目标目录

如果需要更具体的定制(比如监控特定文件类型、添加通知功能等),请告诉我您的具体需求!

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