Python实现实时文件监控

来自CloudWiki
Heart讨论 | 贡献2020年8月12日 (三) 14:31的版本 (创建页面,内容为“Python实现实时文件监控 在我们业务运维中,监控无处不在,我们对业务运行状态做监控,一旦业务故障,我们提前同志运维…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转至: 导航搜索

Python实现实时文件监控 在我们业务运维中,监控无处不在,我们对业务运行状态做监控,一旦业务故障,我们提前同志运维人员,把风险降到最低。

当然要查看业务的运行状态是否正常,我们一般从以下几个方面来判断: (1)业务接口的状态码是否正常 (2)业务接口的返回内容是否正常 (3)业务端口是否正常 (4)对业务程序的生成的日志内容进行判断

Python实现实时文件监控几种方案:

准备好S_mail.py代码

  1. coding:utf-8

import smtplib from email.mime.text import MIMEText

class SendEMail(object):

   # 定义第三方 SMTP 服务
   def __init__(self):
       self.mail_host = "smtp.163.com"  # SMTP服务器
       self.mail_user = "15610347662@163.com"  # 用户名
       self.mail_pass = "APLT"  # 密码
       self.sender = '15610347662@163.com'  # 发件人邮箱
       self.smtpObj = smtplib.SMTP_SSL(self.mail_host, 465)
       self.smtpObj.login(self.mail_user,self.mail_pass)  # 登录验证
   def sendmail(self,receivers,title,content):
       message = MIMEText(content,'plain','utf-8')  # 内容, 格式, 编码
       message['From'] = "{}".format(self.sender)
       message['To'] = ",".join(receivers)
       message['Subject'] = title
       try:
           self.smtpObj.sendmail(self.sender, message['To'].split(','), message.as_string())  # 发送
           print("mail has been send successfully.")
       except smtplib.SMTPException as e:
           print(e)

if __name__ == '__main__':

   sm = SendEMail()

sm.sendmail(['15610347662@163.com'], '主题', '正文') 我们将代码和测试日志放在同一个文件夹下测试

方案一调用Linux的tailf实现


  1. coding:utf-8

import subprocess from S_mail import SendEMail

logfile = "pay-api_error.log" cmd = 'tailf -1{0}'.format(logfile) key_word="heart"

pp = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) while True:

   line = pp.stdout.readline().strip()
   line = line.decode()
   if key_word in line:
       print("有{0},发送紧急警告".format(key_word))
       sm = SendEMail()
       sm.sendmail(['15610347662@163.com'],"主题","正文")

1-3行:导入subprocess用于调用shell,from S_mail import SendEMail导入邮件类

5-7行:定义变量,执行的shell命令,文件路径和关键字

最后调用shell去执行,strip()方法用于移除字符串头尾指定的字符,