liunx pyinotify的安装和使用
介绍此功能是检测目录的操作的事件
1.安装
在百度云盘下载或者在gits上下载安装包
链接:https://pan.baidu.com/s/1Lqt872YEgEo_bNPEnEJMaw
提取码:bjl2
# git clone https://github.com/seb-m/pyinotify.git
# cd pyinotify/
# ls
# python setup.py install
2.使用在代码中直接导入就可以
# -*- coding: utf-8 -*-
# !/usr/bin/env python
import os
import Queue
import datetime
import pyinotify
import logging
#debug
import threading,time pos = 0
save_pos = 0
filename ="" #
filename1 =""
pathname ="" class Singleton(type):
def __call__(cls, *args, **kwargs):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance
def __new__(cls, name, bases, dct):
return type.__new__(cls, name, bases, dct) def __init__(cls, name, bases, dct):
super(Singleton, cls).__init__(name, bases, dct) class AuditLog(object):
__metaclass__ = Singleton
def __init__(self): FORMAT = ('%(asctime)s.%(msecs)d-%(levelname)s'
'[%(filename)s:%(lineno)d:%(funcName)s]: %(message)s')
DATEFMT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging.DEBUG, format=FORMAT,datefmt=DATEFMT) logging.debug("__init__")
self.log_queue = Queue.Queue(maxsize=1000)
self.str = "AuditLog" def start(self,path): # path as: /var/log/auth.log
try:
print "start:",threading.currentThread()
if( not os.path.exists(path)):
logging.debug("文件路径不存在")
return
logging.debug("文件路径:{}".format(path))
global pathname
pathname = path # # 输出前面的log
# printlog()
file = path[:path.rfind('/')] global filename
global filename1
filename = path[path.rfind('/')+1:]
filename1 = filename + ".1"
print "filename:",filename," filename1 ",filename1
# watch manager
wm = pyinotify.WatchManager()
wm.add_watch(file, pyinotify.ALL_EVENTS, rec=True)
eh = MyEventHandler()
# notifier
notifier = pyinotify.Notifier(wm, eh)
notifier.loop() except Exception as e:
logging.error('[AuditLog]:send error: %s',str(e))
return def read_log_file(self):
global pos
global save_pos
try:
# if( not os.pathname.exists(pathname)):
# logging.debug("读取的文件不存在")
# return
fd = open(pathname)
if pos != 0:
fd.seek(pos, 0)
while True:
line = fd.readline()
if line.strip():
logging.debug("put queue:{}".format(line.strip()))
try:
self.log_queue.put_nowait(line.strip())
except Queue.Full:
logging.warn('send_log_queue is full now') pos = fd.tell()
save_pos = pos
else:
break
fd.close()
except Exception, e:
logging.error('[AuditLog]:send error: %s',str(e)) def read_log1_file(self): try:
global save_pos
global pos
pos = 0
pathname1 = pathname + ".1"
# if( not os.pathname1.exists(pathname1)):
# logging.debug("读取的文件不存在")
# return
fd = open(pathname1)
if save_pos != 0:
fd.seek(save_pos, 0)
while True:
line = fd.readline()
if line.strip():
if save_pos > fd.tell() :
print save_pos," ",fd.tell()
continue
try:
self.log_queue.put_nowait(line.strip())
logging.debug("put queue:{}".format(line.strip()))
except Queue.Full:
logging.warn('send_log_queue is full now') else:
save_pos = 0
break
fd.close()
except Exception, e:
logging.error('[AuditLog]:send error: %s',str(e)) def __del__(self):
print "del" class MyEventHandler(pyinotify.ProcessEvent): print "MyEventHandler :",threading.currentThread()
def __init__(self):
print "MyEventHandler __init__"
self.auditLogObject = AuditLog()
print self.auditLogObject.str
# 当文件被修改时调用函数
def process_IN_MODIFY(self, event): #文件修改
print "process_IN_MODIFY",event.name def process_IN_CREATE(self, event): #文件创建
# logging.debug("process_IN_CREATE")
print "create event:", event.name
# log.log.1
global save_pos
try: if(event.name == filename):
print "=="
self.auditLogObject.read_log1_file()
else:
logging.debug("审计的文件不相同{} {}".format(filename1).format(event.name))
except Exception as e:
logging.error('[AuditLog]:send error: %s',str(e)) def process_IN_DELETE(self, event): #文件删除
# logging.debug("process_IN_DELETE")
print "delete event:", event.name def process_IN_ACCESS(self, event): #访问
# logging.debug("process_IN_ACCESS")
print "ACCESS event:", event.name def process_IN_ATTRIB(self, event): #属性
# logging.debug("process_IN_ATTRIB")
print "ATTRIB event: 文件属性", event.name def process_IN_CLOSE_NOWRITE(self, event):
# logging.debug("process_IN_CLOSE_NOWRITE")
print "CLOSE_NOWRITE event:", event.name def process_IN_CLOSE_WRITE(self, event): # 关闭写入
# logging.debug("process_IN_CLOSE_WRITE")
print "CLOSE_WRITE event:", event.name
try:
if(event.name == filename):
self.auditLogObject.read_log_file() else:
logging.debug("文件名不对 不是审计文件")
return except Exception as e:
logging.error('[AuditLog]:send error: %s',str(e)) def process_IN_OPEN(self, event): # 打开
# logging.debug("process_IN_OPEN")
print "OPEN event:", event.name def Producer(): try:
auditLogObj = AuditLog()
auditLogObj.start("./log/log.log") except Exception as e:
logging.error('[auditLog]:send error: %s',str(e)) def Consumer(): try:
print "Consumer"
auditLogObject = AuditLog()
print auditLogObject.str
while True:
print "ddd"
time.sleep(1) while auditLogObject.log_queue.qsize() != 0 :
print "queue size",auditLogObject.log_queue.qsize()
print auditLogObject.log_queue.get()
# time.sleep(5) except Exception as e:
logging.error('[AuditLog]:send error: %s',str(e)) if __name__ == '__main__': # a = threading.Thread(target=Producer,)
# a.start()
b = threading.Thread(target=Consumer,)
b.start()
liunx pyinotify的安装和使用的更多相关文章
- Libevent2.1.8版在Liunx中编译安装遇到的问题
Libevent2.1.8版在Liunx中编译安装遇到的问题 前言:在网上找了很久,都没有一个明确的解决方法,通过分析可能的原因,将自己实际操作及解决的成功结果记录如下,以供遇到相似的问题,能提供思路 ...
- liunx环境下安装mysql数据库
一:如果你的机器上之前安装有mysql数据库,先进行卸载 (1)需要先将它的文件删除 (2)同时注意删除老板本的etc/my.cnf文件和/etc/mysql目录,这两个文件控制的是mysql的一些配 ...
- liunx环境下安装禅道
环境: vm12.5.2 CentOS-7-x86_64 ZenTaoPMS.9.1.stable.zbox_64 SecureCRT 8.0 因为liunx环境下配置apache, php, mys ...
- liunx下Oracle安装
1. 引言 将近一个月没有更新博客了,最近忙着数据库数据迁移工作:自己在服务器上搭建了oracle数据库,一步步走下来遇见很多BUG:现在自己记录下,方便以后有用上的地方: 2. 准备工作 oracl ...
- Liunx之MySQL安装与主从复制
MYSQL安装(mariadb) MariaDB数据库管理系统是MySQL的一个分支,主要由开源社区在维护,采用GPL授权许可. 开发这个分支的原因之一是:甲骨文公司收购了MySQL后,有将MySQL ...
- liunx系统中安装lua以及torch
一直在用pytorch,最近在做项目的时候,遇到了torch的开源代码,所以又开始不得不接触torch以及他所依赖的环境lua. liunx下lua环境的配置代码如下: ''' curl -R -O ...
- liunx 服务器下面安装mysql8.0
闲来无事,准备自己搭建一个服务器高点事情,不可避免的就是需要使用到mysql数据库了.在Linux系统安装MySQL8.0,网上已经有很多的教程了,到自己安装的时候却发现各种各样的问题,现在把安装过程 ...
- liunx检查与安装软件包
检查软件包# rpm -qa | grep 例如:# rpm -qa | grep make检查make包 安装软件包 yum install 例如:yum install unixODBC安装un ...
- Liunx下全局安装 Composer
我把它放在系统的PATH目录中,这样就能在全局访问它. curl -sS https://getcomposer.org/installer | php mv composer.phar /usr/l ...
随机推荐
- epoll简介 与 UDP server的实现
Abstractepoll是Linux内核为处理大批量句柄而作了改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著减少程序在大量并发连接中只有少量活跃的情况下的系 ...
- JMX简介及was上的使用
参考文章:https://www.ibm.com/developerworks/cn/websphere/library/techarticles/0908_sunyan_jmxdeploy/inde ...
- [maven]idea+maven的多项目依赖
如下两个项目: test-main test-utils 其中test-main需要引用test-utils. 最终效果如下: 实现步骤: 1:新建一个Empty Project作为框架项目 输入框架 ...
- JAVA 基础编程练习题45 【程序 45 被 9 整除】
45 [程序 45 被 9 整除] 题目:判断一个素数能被几个 9 整除 package cskaoyan; public class cskaoyan45 { public static void ...
- Spring Aop(三)——Pointcut表达式介绍
转发地址:https://www.iteye.com/blog/elim-2395255 3 Pointcut表达式介绍 3.1 表达式类型 标准的Aspectj Aop的pointcut的表达式类型 ...
- swift 第六课 scrollview xib 的使用
现在 xib,stroyBoard 这种图形话的编辑写代码,越来越简单.以前scrollview 这样的控件不会用xib ,网上查了 好多的资料.现在把步骤逐渐的写出来, 这里顺便写个Demo ,是一 ...
- EasyNetQ使用(一)【介绍】
EasyNetQ 是一个容易使用,专门针对RabbitMQ的 .NET API. 假如你尽可能快的想去安装和运行RabbitMQ,请去看入门指南.EasyNetQ是为了提供一个尽可能简洁的适用与Rab ...
- Cache数据库新增用户并分配权限(Caché)
1.通过浏览器登录管理中心,Caché自带的客户端工具是网页的,访问地址: http://localhost:57772/csp/sys/UtilHome.csp 2.选择功能链接:系统管理- ...
- scalaTest的初步使用
1. 概述 ScalaTest是scala生态系统中最流行和灵活的测试工具,可以测试scala.js.java代码. 2. ScalaTest的特性 a. ScalaTest的核心是套件(suite) ...
- 【编程开发】MD5和RSA
MD5和RSA是网络传输中最常用的两个算法,了解这两个算法原理后就能大致知道加密是怎么一回事了.但这两种算法使用环境有差异,刚好互补. (1)MD5 MD5(单向散列算法)的全称是Message-Di ...