1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
from __future__ import absolute_import, unicode_literals
import os import datetime import logging import logging.config
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header from email.mime.application import MIMEApplication import smtplib
name = datetime.datetime.now().strftime("%Y%m%d%H%M%S") base_path = '/root/xxxx/temp' zip_path = '/root/xxxx/backup/{}.tar.bz2'.format(name)
def set_logging(): """"""
log_dir, log_file = '/root/xxxx/logs', '/root/xxxx/logs/backup.log'
if not os.path.exists(log_dir): os.mkdir(log_dir)
if not os.path.exists(log_file): open(log_file, 'w')
DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'formatone': { 'format': '[%(asctime)s] %(levelname)s : %(message)s', } }, 'handlers': { 'file': { 'level': 'DEBUG', 'filename': '/root/xxxx/logs/backup.log', 'formatter': 'formatone', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 100 * 1024 * 1024, 'backupCount': 10, }, }, 'loggers': { 'backup': { 'handlers': ['file'], 'level': 'INFO', }, } }
logging.config.dictConfig(DEFAULT_LOGGING)
def zip_files(): """zip files""" os.system('tar -cjf {} -C {} data'.format(zip_path, base_path))
def sendmail(): """send mail""" set_logging() zip_files()
logger = logging.getLogger('backup')
mail_from, password = 'xxxxxxx@aliyun.com', 'xxxxxxx' mail_to = 'xxxxx@qq.com' smtp_server = 'smtp.aliyun.com'
msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'send backup files {}'.format(name) msgRoot['From'] = '{}<{}>'.format(Header('backup', 'utf-8'), mail_from) msgRoot['To'] = mail_to
msgText = MIMEText('backup files', 'plain', 'utf-8') msgRoot.attach(msgText)
zip_con = MIMEApplication(open(zip_path,'rb').read()) zip_con.add_header('Content-Disposition', 'attachment', filename='{}.tar.bz2'.format(name)) msgRoot.attach(zip_con)
try: server = smtplib.SMTP_SSL(smtp_server) server.login(mail_from, password) server.sendmail(mail_from, mail_to, msgRoot.as_string()) server.quit() logger.info('send {} backup files success'.format(name)) except Exception, e: logger.error('send {} failed {}'.format(name, e)) sendmail()
if __name__ == '__main__': sendmail()
|