首页 > 代码库 > 利用python监控文件被修改
利用python监控文件被修改
需求:
利用python编写监控程序,监控一个文件目录,当目录下的文件发生改变时,实现有修改就发报警邮件
邮件使用QQ邮箱,需要开启smtp,使用手机发生短信,腾讯会给你发邮箱密码。如下所示:
把这个密码填到程序中。
python版本
[root@ftp 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.程序代码如下:
监控主程序
[root@ftp 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 = "11111111@qq.com" ‘‘‘发邮件账号‘‘‘ to = "22222222@qq.com" ‘‘‘接收邮件账号‘‘‘ 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)
发生邮件程序
[root@ftp 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("11111111@qq.com","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 = "11111111@qq.com" to = "22222222@qq.com" send(content,title,froms,to) ‘‘‘
3.实战测试如下:
本文出自 “知识改变命运” 博客,请务必保留此出处http://ahtornado.blog.51cto.com/4826737/1949661
利用python监控文件被修改
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。