utils_daily_logs_send.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 设置每天 23:59 执行, 读取当天数据库中, 所有日志, 发送到指定邮箱
  4. '''
  5. import time
  6. import os
  7. import pymongo
  8. import smtplib
  9. from email.mime.text import MIMEText
  10. from email.header import Header
  11. import tools_load_config
  12. config_json = tools_load_config.load_config()
  13. base_project = tools_load_config.get_base_path()
  14. PROJECT_NAME = config_json.get('PROJECT_NAME')
  15. DB_USER = config_json.get('DB_USER')
  16. DB_PASSWORD = config_json.get('DB_PASSWORD')
  17. DB_IP = config_json.get('DB_IP')
  18. DB_PORT = config_json.get('DB_PORT')
  19. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  20. MAIL_HOST = config_json.get('MAIL_HOST')
  21. MAIL_USER = config_json.get('MAIL_USER')
  22. MAIL_PASS = config_json.get('MAIL_PASS')
  23. MAIL_SENDER = config_json.get('MAIL_SENDER')
  24. MAIL_RECEIVERS = config_json.get('MAIL_RECEIVERS')
  25. now_day = time.strftime('%Y-%m-%d', time.localtime())
  26. rss_base_url = 'http://home.erhe.link:20002/xmlfile/'
  27. class LogsHandle(object):
  28. def __init__(self):
  29. self.now_day = time.strftime('%Y-%m-%d', time.localtime())
  30. db = 'logs'
  31. collection = 'logs_' + self.now_day
  32. self.mongo = MongoHandle(db=db, collection=collection, del_db=False, del_collection=False, auto_remove=0)
  33. def logs_send(self):
  34. subject = 'auto collection logs'
  35. title = 'auto collection - daily logs: {}'.format(self.now_day)
  36. text = ''
  37. # TODO
  38. # 从 mongodb 读取日志, 拼接 text, 发送邮件
  39. # 查询所有文档
  40. cursor = self.mongo.collection.find()
  41. # 遍历结果集
  42. for record in cursor:
  43. text += "logs_source: {}, logs_detail: {}, state: {} logs_create_time: {}\n\n".format(record.setdefault('title'),
  44. record.setdefault('content'),
  45. record.setdefault('state'),
  46. record.setdefault('create_datetime'),
  47. )
  48. S = SendEmail(subject=subject, title=title, text=text)
  49. S.send()
  50. class MongoHandle(object):
  51. def __init__(self, db, collection, del_db=False, del_collection=False, auto_remove=0):
  52. self.client = pymongo.MongoClient(MONGO_LINK)
  53. self.db = db
  54. self.collection = collection
  55. if del_db and db:
  56. # 检查数据库是否存在
  57. if db in self.client.list_database_names():
  58. # 删除数据库
  59. self.client.drop_database(db)
  60. self.db = self.client[db]
  61. if del_collection and self.collection:
  62. # 检查集合是否存在
  63. if self.collection in self.db.list_collection_names():
  64. # 删除集合
  65. self.db.drop_collection(collection)
  66. self.collection = self.db[collection]
  67. if auto_remove:
  68. self.auto_remove_data(auto_remove)
  69. def write_data(self, data):
  70. self.collection.insert_one(data)
  71. def auto_remove_data(self, day):
  72. for data in self.collection.find({'create_time': {'$lt': int(time.time()) - day * 24 * 60 * 60}}):
  73. self.collection.delete_one({'_id': data['_id']})
  74. class SendEmail(object):
  75. def __init__(self, subject='auto subject', title='auto title', text='auto text') -> None:
  76. # 第三方 SMTP 服务
  77. self.mail_host = MAIL_HOST # 设置服务器
  78. self.mail_user = MAIL_USER # 用户名
  79. self.mail_pass = MAIL_PASS # 口令
  80. self.sender = MAIL_SENDER
  81. self.receivers = [MAIL_RECEIVERS]
  82. self.subject = subject
  83. self.title = title
  84. self.text = text
  85. def send(self):
  86. message = MIMEText(self.text, 'plain', 'utf-8')
  87. message['From'] = Header(self.title, 'utf-8')
  88. message['To'] = Header("auto collection", 'utf-8')
  89. subject = self.subject
  90. message['Subject'] = Header(subject, 'utf-8')
  91. try:
  92. smtpObj = smtplib.SMTP()
  93. smtpObj.connect(self.mail_host, 25)
  94. smtpObj.login(self.mail_user, self.mail_pass)
  95. smtpObj.sendmail(self.sender, self.receivers, message.as_string())
  96. print("邮件发送成功")
  97. except smtplib.SMTPException:
  98. print("Error: 无法发送邮件")
  99. if __name__ == '__main__':
  100. print("发送当天日志:start")
  101. LogsHandle().logs_send()
  102. print("发送当天日志:done")