需求:
利用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.实战测试如下: