«

linux如何监测/usr/share/nginx/html下文件的新建消息,并记录到/var/log/files/filenew.log文件下的python3脚本

qkabcd 发布于 阅读:956 IT技术


在Linux系统中,你可以使用inotify工具来监测文件系统事件,如文件的新建。下面是一个使用Python 3和pyinotify库来监测/usr/share/nginx/html目录下文件新建事件的脚本示例。由于你要求不使用pip安装任何包,我会假设pyinotify已经安装在系统上。

import pyinotify
import logging

设置日志

log_file = '/var/log/files/filenew.log'
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(message)s')

定义事件处理类

class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
logging.info(f"New file created: {event.pathname}")

创建WatchManager对象

wm = pyinotify.WatchManager()

设置监控事件

mask = pyinotify.IN_CREATE # 监控新建文件事件

创建事件处理对象

handler = EventHandler()

创建Notifier对象

notifier = pyinotify.Notifier(wm, handler)

添加监控路径

wm.add_watch('/usr/share/nginx/html', mask, rec=True)

开始监控

notifier.loop()
将上述脚本保存为monitor_new_files.py,并赋予执行权限:

chmod +x monitor_new_files.py
然后运行脚本:

./monitor_new_files.py
脚本将开始监控/usr/share/nginx/html目录下的文件新建事件,并将相关信息记录到/var/log/files/filenew.log文件中。

请注意,这个脚本需要pyinotify库,如果系统中没有安装,你需要手动安装它,或者使用其他方法来实现监控,例如使用inotifywait命令行工具结合Python脚本。

如果你不能安装pyinotify,以下是一个使用inotifywait的替代方案:

import subprocess
import logging

设置日志

log_file = '/var/log/files/filenew.log'
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(message)s')

监控函数

def monitor_directory(path):
cmd = ['inotifywait', '-m', '-e', 'create', path]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

while True:
    output = process.stdout.readline()
    if output:
        logging.info(f"New file created: {output.strip().split(' ', 1)[1]}")

开始监控

monitor_directory('/usr/share/nginx/html')
保存此脚本并运行,它将使用inotifywait来监控指定目录。如果inotifywait命令不可用,你需要安装inotify-tools包。

改进可以监控子文件夹的
import subprocess
import logging

设置日志

log_file = '/var/log/files/filenew.log'
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(message)s')

监控函数

def monitor_directory(path):
cmd = ['inotifywait', '-m', '-r', '-e', 'create', path]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while True:
    output = process.stdout.readline()
    if output:
        # 将字节转换为字符串
        output_str = output.decode('utf-8').strip()
        # 输出格式是经过自定义的,直接就是完整路径
        logging.info(f"{output_str}")

开始监控

monitor_directory('/usr/share/nginx/html')

linux