简单备份文件并发送到指定邮箱

背景

一哥们发了个诉求,总觉得自己的服务器不安全,想搞个定时备份文件并发送到自己的邮箱

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 命令进行打包

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 简单小结

业务比较简单,实现也比较简单,没啥可说的


青阳半雪
点滴记录,步步成长

现实与完美之间

1.6k 声望
24 粉丝
0 条评论
推荐阅读
Django | 信号使用思考
重拾些许关于信号模块使用的记忆,记录对于 Django 信号使用的思考。本文使用的 Django 的版本是 4.21 源码注释 {代码...} 2 函数清单2.1 _make_id 方法 {代码...} 首先认真分析下其业务实现,target 参数是接收...

青阳半雪阅读 447

基于Sanic的微服务基础架构
使用python做web开发面临的一个最大的问题就是性能,在解决C10K问题上显的有点吃力。有些异步框架Tornado、Twisted、Gevent 等就是为了解决性能问题。这些框架在性能上有些提升,但是也出现了各种古怪的问题难以...

jysong6阅读 3.9k评论 3

滚蛋吧,正则表达式!
你是不是也有这样的操作,比如你需要使用「电子邮箱正则表达式」,首先想到的就是直接百度上搜索一个,然后采用 CV 大法神奇地接入到你的代码中?

良许4阅读 2.2k

又一款眼前一亮的Linux终端工具!
今天给大家介绍一款最近发现的功能十分强大,颜值非常高的一款终端工具。这个神器我是在其他公众号文章上看到的,但他们都没把它的强大之处介绍明白,所以我自己体验一波后,再向大家分享自己的体验。

良许5阅读 1.8k

FastAPI性能碾压Flask?
不止一次的听过,FastAPI性能碾压Flask,直追Golang,不过一直没有测试过,今天闲着没事测试一下看看结果。不知道是哪里出了问题,结果大跌眼镜。

二毛erma02阅读 10.1k评论 3

封面图
程序员适合创业吗?
大家好,我是良许。从去年 12 月开始,我已经在视频号、抖音等主流视频平台上连续更新视频到现在,并得到了不错的评价。每个视频都花了很多时间精力用心制作,欢迎大家关注哦~考虑到有些小伙伴没有看过我的视频,...

良许3阅读 1.8k

Python之如何优雅的重试
为了避免偶尔的网络连接失败,需要加上重试机制,那么最简单的形式就是在对应的代码片段加一个循环,循环体里使用异常捕获,连接成功时退出循环,否则就重复执行相关逻辑,此时修改之后的函数f如下

Harpsichord12073阅读 7.3k

现实与完美之间

1.6k 声望
24 粉丝
宣传栏