利用python监控文件被修改
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用python监控文件被修改相关的知识,希望对你有一定的参考价值。
需求:
利用python编写监控程序,监控一个文件目录,当目录下的文件发生改变时,实现有修改就发报警邮件
邮件使用QQ邮箱,需要开启smtp,使用手机发生短信,腾讯会给你发邮箱密码。如下所示:
把这个密码填到程序中。
python版本
[[email protected] day01]# python Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56) [GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
2.程序代码如下:
监控主程序
[[email protected] day01]# cat montest.py #!/usr/bin/env python #coding:utf-8 import sys import pyinotify from sendMail import send try: path = sys.argv[1] except: raise(AttributeError("has no attribute path")) class MyEvent(pyinotify.ProcessEvent): def process_IN_MODIFY(self,event): ‘‘‘print("hell world") print ("%s be chandg "event.name) ‘‘‘ content = "%s be change" %(path+event.name) title = "refine‘s mail" froms = "[email protected]" ‘‘‘发邮件账号‘‘‘ to = "[email protected]" ‘‘‘接收邮件账号‘‘‘ send(content,title,froms,to) print (content) def main(path): vm = pyinotify.WatchManager() vm.add_watch(path,pyinotify.ALL_EVENTS,rec = True) event = MyEvent() notifier = pyinotify.Notifier(vm,event) notifier.loop() main(path)
发生邮件程序
[[email protected] day01]# cat sendMail.py #!/usr/bin/env python #coding:utf-8 import smtplib from email.mime.text import MIMEText def send(content,title,froms,*to): msg = MIMEText(content,"plain","utf-8") msg["Subject"]= title msg["From"]= froms msg["To"] = ",".join(to) server = smtplib.SMTP_SSL("smtp.qq.com",465) server.login("[email protected]","zqyricvcbed") ‘‘‘此处写你发邮件的qq和密码‘‘‘ server.sendmail(froms,list(to),msg.as_string()) server.quit() if __name__ == ‘__main__‘: ‘‘‘ content = "hello I am alvin" title = "alvin‘s mail" froms = "[email protected]" to = "[email protected]" send(content,title,froms,to) ‘‘‘
3.实战测试如下:
本文出自 “知识改变命运” 博客,请务必保留此出处http://ahtornado.blog.51cto.com/4826737/1949661
以上是关于利用python监控文件被修改的主要内容,如果未能解决你的问题,请参考以下文章
在linux下使用inotify监控,能不能够知道监控目录下子目录中是哪个文件被修改了。。。求方法。。。
windows下,python文件监控,python监听文件修改,php文件监控,php监听文件修改
Spring Cloud实战之初级入门— 利用Hystrix实现服务熔断与服务监控