Linux-通過inotifywait監控目錄及文件 inotifywait命令的使用此處就不寫了;可以參考文章:https://www.cnblogs.com/martinzhang/p/4126907.html inotifywait命令是工具包 inotify-tools 裡面的,可以直接通過 ...
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:[email protected] # 引入相應的模塊 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 收件人可以是多個,["[email protected]","[email protected]"], 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:\Users\YJ\Desktop\aaa.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(["[email protected]",], 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
查看郵件: