Linux-通过inotifywait监控目录及文件
inotifywait命令的使用此处就不写了;可以参考文章:https://www.cnblogs.com/martinzhang/p/4126907.html
inotifywait命令是工具包 inotify-tools 里面的,可以直接通过yum安装 yum install inotify-tools -y
此处通过inotifywait监控某个目录及里面的文件,(create、delete、modify)。通过Python发送邮件告知:
(1)编写邮件脚本/tmp/mail.py
# !/usr/bin/env python # -*- coding:utf-8 -*- # Date:2019-02-13 # Desc: 用于发送邮件脚本,使用方法:python3.6 脚本名字(mail.py) 主题 邮件内容 附件路径 # By:yanjieli # Email:381347268@qq.com # 引入相应的模块 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email import encoders from email.utils import parseaddr, formataddr import sys class SendMail(object): def __init__(self): self.fromUser = "******@qq.com" self.userPasswd = "vpqnntvrrflibghe" # 此处是qq邮箱授权码, 不是登录密码 self.smtpAddr = "smtp.qq.com" # 构造邮件结构 # toAddrs 收件人可以是多个,["xxx@qq.com","xxx@qq.com"], subject 邮件的主题, msg 邮件的内容 def mailStructure(self, toAddrs, subject, msg, filePath): # 邮件对象: mailMsg = MIMEMultipart() mailMsg['Subject'] = ("Hello Administrators <%s>" % subject) mailMsg['From'] = ("Python管理员 <%s>" % self.fromUser) mailMsg['To'] = ','.join(toAddrs) # 邮件正文是MIMEText : mailMsg.attach(MIMEText('<html><body><h1>%s</h1>' % (msg) + '<p><img src="cid:1"></p>' + '</body></html>', 'html','utf-8')) #mailMsg.attach(MIMEText(msg, 'html', 'utf-8')) # 发送文件附件, 需要用到附件对象MIMEBase对象, 需要引入from email.mime.multipart import MIMEBase # 添加附件就是加上一个MIMEBase,从本地读取一个文件: with open(filePath, "rb") as f: #with open(r"C:UsersYJDesktopaaa.txt", "rb") as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase("txta", "txt", filename="info.txt") # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='info.txt') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: encoders.encode_base64(mime) # 添加到MIMEMultipart: mailMsg.attach(mime) return mailMsg.as_string() # 发送邮件 def sendMail(self, toAddrs, subject, msg,filePath): mailMsg_as_string = self.mailStructure(toAddrs, subject, msg,filePath) # 连接服务器发送邮件 try: server = smtplib.SMTP_SSL(self.smtpAddr, 465) server.connect(self.smtpAddr) # 连接smtp服务器 server.login(self.fromUser, self.userPasswd) # 登录邮箱 server.sendmail(self.fromUser, toAddrs, mailMsg_as_string) # 发送邮件 server.quit() except Exception: print("Error: unable to send email") subject = sys.argv[1] # 邮件主题 msg = sys.argv[2] # 邮件内容 filePath = sys.argv[3] # 附件路径 a = SendMail() #实例化一个对象 a.sendMail(["381347268@qq.com",], subject, msg, filePath) #执行sendMail方法
(2)编写shell监控脚本/tmp/test.sh
#!/bin/bash #date:20190213 #explain:监控目录是否发生变化 #by:YJLI CHECKDIR="/tmp/test" #监控目录路径 LOG="/tmp/inot.log" #日志存放路径 PYTHONMAIL="/tmp/mail.py" #发送邮件脚本路径 function CheckDir { inotifywait -mrq --timefmt '%y-%m-%d %H:%M' --format '%T %f %e' -e 'create,delete,modify,moved_to' $CHECKDIR|while read event do INO_TIME=$(echo $event | awk '{print $1,$2}') # 把inotify输出切割 把时间部分赋值给INO_TIME INO_FILE=$(echo $event | awk '{print $3}') # 把inotify输出切割 把文件路径部分赋值给INO_FILE INO_EVENT=$(echo $event | awk '{print $4}') # 把inotify输出切割 把事件类型部分赋值给INO_EVENT if [[ $INO_EVENT = 'CREATE' ]] && [[ $INO_FILE != .* ]];then # 判断事件类型(create) echo "`date '+%Y-%m-%d %H:%M'` create file: $INO_FILE" >> $LOG /usr/bin/python3.5 $PYTHONMAIL create "创建了一个文件:${INO_FILE},详情见附件" $LOG elif [[ $INO_EVENT = 'CREATE,ISDIR' ]];then echo "`date '+%Y-%m-%d %H:%M'` create dir: $INO_FILE" >> $LOG /usr/bin/python3.5 $PYTHONMAIL create "创建了一个目录:${INO_FILE},详情见附件" $LOG fi if [[ $INO_EVENT = 'DELETE' ]] && [[ $INO_FILE != .* ]];then # 判断事件类型(delete) echo "`date '+%Y-%m-%d %H:%M'` delete file: $INO_FILE" >> $LOG /usr/bin/python3.5 $PYTHONMAIL delete "删除了一个文件:${INO_FILE},详情见附件" $LOG elif [[ $INO_EVENT = 'DELETE,ISDIR' ]];then echo "`date '+%Y-%m-%d %H:%M'` delete dir: $INO_FILE" >> $LOG /usr/bin/python3.5 $PYTHONMAIL delete "删除了一个目录:${INO_FILE},详情见附件" $LOG fi if [[ $INO_EVENT = 'MODIFY' ]] && [[ $INO_FILE != .* ]];then # 判断事件类型(modify) echo "`date '+%Y-%m-%d %H:%M'` modify file: $INO_FILE" >> $LOG /usr/bin/python3.5 $PYTHONMAIL delete "修改了一个文件:${INO_FILE},详情见附件" $LOG fi done } CheckDir
(3)执行shell脚本并放在后台执行
[root@courtoap tmp]# nohup bash /tmp/test.sh & #执行脚本并放在后台执行
(4)测试
[root@courtoap test]# cd /tmp/test #进入到测试目录 [root@courtoap test]# ls #查看当前目录文件 [root@courtoap test]# touch file1 #创建一个新的文件 [root@courtoap test]# mkdir dir1 #创建一个新的目录 [root@courtoap test]# echo test >> file1 #编辑file1文件 [root@courtoap test]# rm -rf file1 #删除file1文件 [root@courtoap test]# touch dir1/dir1_file #在dir1目录里面再创建一个文件 [root@courtoap test]# cat /tmp/inot.log #查看生成的日志 2019-02-13 16:00 create file: file1 2019-02-13 16:00 create dir: dir1 2019-02-13 16:00 modify file: file1 2019-02-13 16:01 delete file: file1 2019-02-13 16:03 create file: dir1_file
查看邮件: