簡單備份文件併發送到指定郵箱

背景

一哥們發了個訴求,總以爲本身的服務器不安全,想搞個定時備份文件併發送到本身的郵箱python

1 實現代碼以下

# -*- coding: utf-8 -*-

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()

2 簡單說明

2.1 打包文件

這個實現比較初級,直接用 shell 命令進行打包shell

def zip_files():
    """zip files"""
    os.system('tar -cjf {} -C {} data'.format(zip_path, base_path))

2.2 發送郵件

這個就不說了,現成的模塊直接拿來用安全

2.3 日誌記錄

加上日誌,能夠很清楚的讓我知道發送狀況以下,示例以下:服務器

[2017-04-14 00:00:03,251] INFO : send 20170414000001 backup files success
[2017-04-14 03:00:02,620] INFO : send 20170414030001 backup files success
[2017-04-14 06:00:02,406] INFO : send 20170414060001 backup files success
[2017-04-14 09:00:02,349] INFO : send 20170414090001 backup files success
[2017-04-14 12:00:02,299] INFO : send 20170414120001 backup files success
[2017-04-14 15:01:04,696] ERROR : send 20170414150001 failed [Errno 110] Connection timed out
[2017-04-14 15:01:05,401] INFO : send 20170414150001 backup files success

2.4 定時處理

定時這個處理,直接使用 crontab 命令,建立個 backup_cron 文件,寫入併發

0 */3 * * *  python /root/xxxxx/backup.py

3 簡單小結

業務比較簡單,實現也比較簡單,沒啥可說的app

相關文章
相關標籤/搜索