监控linux空间变化,Linux监控文件变化及主动上报实现

一、说明

最近在做一些主机的自动化检查操作,每次都是定时主动去扫描。这种方式一是实时性不佳,二是扫描时会陡然给中心机很大的压力。后来想有没有一种主机上的配置如果发生变动就能主动上报的机制,如果能主动上报一又解决了实时性问题,二也解决了中心机压力的问题。

二、Shell脚本实现

2.1 基本使用

安装:

yum install inotify-tools

使用格式:

# 使用格式

inotifywait [-hcmrq] [-e ] [-t ] [--format ] [--timefmt ] [ ... ]

# 最常用格式举例

# 持续监控/etc/passwd文件被修改事件

inotifywait-m -e modify /etc/passwd# 持续监控/tmp目录及其子目录下的所有事件

inotifywait-m -r /tmp

2.2 实现示例

在一个终端窗口中开启监控:

bb370cf3375f9d2619f6593b53512d30.png

在另外一个终端窗口中执行命令:

71c420c2c7f61880e1c7c1adfeac0e16.png

再回头看第一个窗口,显示如下:

34a4ad47a41143914dc2a7057a119040.png

三、Python实现

3.1 基本使用

安装:

pip install pyinotify

使用格式:

(base) [root@ls-virtual-machine ~]# python -m pyinotify -h

Usage: pyinotify.py [options] [path1] [path2] [pathn]

Options:-h, --help show this help message and exit-v, --verbose Verbose mode-r, --recursive Add watches recursively on paths-a, --auto_add Automatically add watches on new directories-g, --glob Treat paths as globs-e EVENT[,...], --events-list=EVENT[,...]

A comma-separated list of events to watch for -see

the documentationforvalid options (defaults to

everything)-s, --stats Display dummy statistics-V, --version Pyinotify version-f, --raw-format Disable enhanced output format.-c COMMAND, --command=COMMAND

Shell command to run upon event

3.2 使用示例

在一个终端窗口中开启监控:

c2571971485fb3095e9d99a7591acf52.png

在另一个终端窗口中执行命令:

a31c4ce4891bfd43a0a98fd25a6665b1.png

再回头看第一个窗口,显示如下:

2d95624cd56f38066ce49d1fc3653288.png

3.3 代码使用示例

将以下代码保存成test.py:

import pyinotify

# Watch Manager

wm=pyinotify.WatchManager()

# 监听文件创建事件和文件删除事件

mask= pyinotify.IN_CREATE |pyinotify.IN_DELETE

class EventHandler(pyinotify.ProcessEvent):

# 如果文件创建事件发生,则要执行的代码

def process_IN_CREATE(self, event):

print(f"Creating: {event.pathname}")

# 如果文件删除事件产生,则要执行的代码

def process_IN_DELETE(self, event):

print(f"Removing: {event.pathname}")

handler=EventHandler()

notifier=pyinotify.Notifier(wm, handler)

wdd= wm.add_watch('/tmp', mask, rec=True)

# 持续监控

notifier.loop()

在一个终端窗口中运行该文件:

d8fa34fbcebac60a01ef716493a56382.png

在另一个终端窗口中执行命令:

c2e269ff532be6d2d581187c0b962773.png

再回头看第一个窗口,显示如下:

ef2f9a2742291fd4173379989e8fbf8a.png

参考:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值