成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

簡單備份文件并發(fā)送到指定郵箱

lingdududu / 3277人閱讀

摘要:背景一哥們發(fā)了個訴求,總覺得自己的服務(wù)器不安全,想搞個定時備份文件并發(fā)送到自己的郵箱實(shí)現(xiàn)代碼如下簡單說明打包文件這個實(shí)現(xiàn)比較初級,直接用命令進(jìn)行打包發(fā)送郵件這個就不說了,現(xiàn)成的模塊直接拿來用日志記錄加上日志,可以很清

背景

一哥們發(fā)了個訴求,總覺得自己的服務(wù)器不安全,想搞個定時備份文件并發(fā)送到自己的郵箱

1 實(shí)現(xiàn)代碼如下
# -*- 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 = "[email protected]", "xxxxxxx"
    mail_to = "[email protected]"
    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 打包文件

這個實(shí)現(xiàn)比較初級,直接用 shell 命令進(jìn)行打包

def zip_files():
    """zip files"""
    os.system("tar -cjf {} -C {} data".format(zip_path, base_path))
2.2 發(fā)送郵件

這個就不說了,現(xiàn)成的模塊直接拿來用

2.3 日志記錄

加上日志,可以很清楚的讓我知道發(fā)送情況如下,示例如下:

[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 命令,創(chuàng)建個 backup_cron 文件,寫入

0 */3 * * *  python /root/xxxxx/backup.py
3 簡單小結(jié)

業(yè)務(wù)比較簡單,實(shí)現(xiàn)也比較簡單,沒啥可說的

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/40708.html

相關(guān)文章

  • Linux定時備份數(shù)據(jù)庫到指定郵箱

    摘要:本文轉(zhuǎn)自豆?jié){下每天備份數(shù)據(jù)庫并發(fā)送到指定郵箱一配置郵箱這里使用的是網(wǎng)易郵箱郵箱的服務(wù),服務(wù)器是。成功收到郵件,沒問題。編寫腳本和定時任務(wù)萬事俱備,接下來要做自動化工作建立一個備份腳本,并使用定時任務(wù)每天執(zhí)行它。 本文轉(zhuǎn)自豆?jié){Melon :linux下每天備份Mysql數(shù)據(jù)庫并發(fā)送到指定郵箱 一、配置郵箱 這里使用的是網(wǎng)易郵箱126郵箱的STMP服務(wù),服務(wù)器是smtp.126.com。...

    hellowoody 評論0 收藏0
  • SegmentFault 技術(shù)周刊 Vol.42 - MySQL:從刪庫到跑路

    摘要:肖鵬微博數(shù)據(jù)庫那些事兒肖鵬,微博研發(fā)中心技術(shù)經(jīng)理,主要負(fù)責(zé)微博數(shù)據(jù)庫相關(guān)的業(yè)務(wù)保障性能優(yōu)化架構(gòu)設(shè)計,以及周邊的自動化系統(tǒng)建設(shè)。經(jīng)歷了微博數(shù)據(jù)庫各個階段的架構(gòu)改造,包括服務(wù)保障及體系建設(shè)微博多機(jī)房部署微博平臺化改造等項目。 showImg(https://segmentfault.com/img/bV24Gs?w=900&h=385); 對于手握數(shù)據(jù)庫的開發(fā)人員來說,沒有誤刪過庫的人生是...

    aboutU 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<