| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- # -*- coding: utf-8 -*-
- '''
- 设置每天 23:59 执行, 读取当天数据库中, 所有日志, 发送到指定邮箱
- '''
- import time
- import os
- import pymongo
- import smtplib
- from email.mime.text import MIMEText
- from email.header import Header
- import tools_load_config
- config_json = tools_load_config.load_config()
- base_project = tools_load_config.get_base_path()
- PROJECT_NAME = config_json.get('PROJECT_NAME')
- DB_USER = config_json.get('DB_USER')
- DB_PASSWORD = config_json.get('DB_PASSWORD')
- DB_IP = config_json.get('DB_IP')
- DB_PORT = config_json.get('DB_PORT')
- MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
- MAIL_HOST = config_json.get('MAIL_HOST')
- MAIL_USER = config_json.get('MAIL_USER')
- MAIL_PASS = config_json.get('MAIL_PASS')
- MAIL_SENDER = config_json.get('MAIL_SENDER')
- MAIL_RECEIVERS = config_json.get('MAIL_RECEIVERS')
- now_day = time.strftime('%Y-%m-%d', time.localtime())
- rss_base_url = 'http://home.erhe.link:20002/xmlfile/'
- class LogsHandle(object):
- def __init__(self):
- self.now_day = time.strftime('%Y-%m-%d', time.localtime())
- db = 'logs'
- collection = 'logs_' + self.now_day
- self.mongo = MongoHandle(db=db, collection=collection, del_db=False, del_collection=False, auto_remove=0)
- def logs_send(self):
- subject = 'auto collection logs'
- title = 'auto collection - daily logs: {}'.format(self.now_day)
- text = ''
- # TODO
- # 从 mongodb 读取日志, 拼接 text, 发送邮件
- # 查询所有文档
- cursor = self.mongo.collection.find()
- # 遍历结果集
- for record in cursor:
- text += "logs_source: {}, logs_detail: {}, state: {} logs_create_time: {}\n\n".format(record.setdefault('title'),
- record.setdefault('content'),
- record.setdefault('state'),
- record.setdefault('create_datetime'),
- )
- S = SendEmail(subject=subject, title=title, text=text)
- S.send()
- class MongoHandle(object):
- def __init__(self, db, collection, del_db=False, del_collection=False, auto_remove=0):
- self.client = pymongo.MongoClient(MONGO_LINK)
- self.db = db
- self.collection = collection
- if del_db and db:
- # 检查数据库是否存在
- if db in self.client.list_database_names():
- # 删除数据库
- self.client.drop_database(db)
- self.db = self.client[db]
- if del_collection and self.collection:
- # 检查集合是否存在
- if self.collection in self.db.list_collection_names():
- # 删除集合
- self.db.drop_collection(collection)
- self.collection = self.db[collection]
- if auto_remove:
- self.auto_remove_data(auto_remove)
- def write_data(self, data):
- self.collection.insert_one(data)
- def auto_remove_data(self, day):
- for data in self.collection.find({'create_time': {'$lt': int(time.time()) - day * 24 * 60 * 60}}):
- self.collection.delete_one({'_id': data['_id']})
- class SendEmail(object):
- def __init__(self, subject='auto subject', title='auto title', text='auto text') -> None:
- # 第三方 SMTP 服务
- self.mail_host = MAIL_HOST # 设置服务器
- self.mail_user = MAIL_USER # 用户名
- self.mail_pass = MAIL_PASS # 口令
- self.sender = MAIL_SENDER
- self.receivers = [MAIL_RECEIVERS]
- self.subject = subject
- self.title = title
- self.text = text
- def send(self):
- message = MIMEText(self.text, 'plain', 'utf-8')
- message['From'] = Header(self.title, 'utf-8')
- message['To'] = Header("auto collection", 'utf-8')
- subject = self.subject
- message['Subject'] = Header(subject, 'utf-8')
- try:
- smtpObj = smtplib.SMTP()
- smtpObj.connect(self.mail_host, 25)
- smtpObj.login(self.mail_user, self.mail_pass)
- smtpObj.sendmail(self.sender, self.receivers, message.as_string())
- print("邮件发送成功")
- except smtplib.SMTPException:
- print("Error: 无法发送邮件")
- if __name__ == '__main__':
- print("发送当天日志:start")
- LogsHandle().logs_send()
- print("发送当天日志:done")
|