当前位置: 移动技术网 > IT编程>脚本编程>Python > python监控文件并且发送告警邮件

python监控文件并且发送告警邮件

2018年08月18日  | 移动技术网IT编程  | 我要评论

瑶源葆春胶囊,北碚区委书记,3u8858

本文实例为大家分享了python监控文件并发送邮件的具体代码,供大家参考,具体内容如下

一、配置文件

import time,datetime 
 
today = time.time() 
time_path = str(today.year) + "/" + str(today.month) + "/" + str(datetime.datetime.now().date()) 
 
monitor_config = { 
 "monitor_file":[ 
  {"key":"py_distribute-datacollect","path":"/home/vagrant/py_distribute/data/" + time_path + "_error.txt","max_size":100}, 
 ], 
 "send_account":"xxxx@qq.com", 
 "license_code":"feruwfpsiwkuibge", # 授权码 
 "rec_account":["xxxx@qq.com"], 
 "host":"smtp.qq.com", 
 "port":465, 
 "sleep_time":60, 
} 

二、监控

#-*- encoding: utf8 -*- 
# 腾讯邮箱授权码 
# feruwfpsiwkuibge 
 
import smtplib 
import logging 
import time 
import os 
from email.mime.text import mimetext 
from monitor_config import monitor_config 
 
format = '[%(asctime)-15s] %(message)s' 
logging.basicconfig(filename = "monitor.txt", level = logging.debug, filemode = "a", format=format) 
 
def get_file_size(file_name): 
 if os.path.exists(file_name): 
  bytes_size = float(os.path.getsize(file_name)) 
  kb = bytes_size/1024 
  mb = kb/1024 
  return mb 
 return 0 
 
def send_email(file_name,key): 
 msg = mimetext(file_name+"文件超过限制,可能存在异常,请处理。项目为:"+key) 
 msg = [key] 
 msg["from"]= monitor_config["send_account"] 
 msg["to"] = monitor_config["rec_account"] 
 try: 
  s = smtplib.smtp_ssl(monitor_config["host"],monitor_config["port"]) 
  s.login(monitor_config["send_account"],monitor_config["license_code"]) 
  s.sendmail(monitor_config["send_account"],monitor_config["rec_account"],msg.as_string()) 
  s.quit() 
  logging.info(file_name + "警告发送成功") 
 except exception as e: 
  logging.exception(e) 
 
# check 
while true: 
 for file in monitor_config["monitor_file"]: 
  file_size = get_file_size(file["path"]) 
  if file_size > file["max_size"]: 
   send_email(file["path"],file["key"]) 
 logging.info("检查完毕") 
 time.sleep(monitor_config["sleep_time"]) 

三、需在qq邮箱设置开启pop3/smtp服务

四、参考

python使用qq邮箱发送email的方法实例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网