Python脚本备份数据库

原创
2016/05/09 16:02
阅读数 183
# coding:utf-8
import subprocess
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
databases=['db1','db2']

def backup(database):
    commandfull="/usr/local/mysql/bin/mysqldump -u%s -p%s %s > %s.sql" %('root','sy2015',database,database)
    subprocess.call(commandfull, shell=True)


def _format_addr(s):
    name,addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr,unicode) else addr))

def sendEMail():
    from_addr = "from@163.com"
    password = "pwd"
    smtp_server = "smtp.163.com"
    to_addr = "to@163.com"

    msg = MIMEText('数据库备份成功!', 'plain', 'utf-8')
    msg['From'] = _format_addr(from_addr)
    msg['To'] = _format_addr(to_addr)
    msg['Subject'] = Header(u'数据库备份信息', 'utf-8').encode()

    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()


if __name__ == '__main__':
    for database in databases:
        backup(database)
sendEMail()



展开阅读全文
打赏
2
2 收藏
分享
加载中
更多评论
打赏
0 评论
2 收藏
2
分享
返回顶部
顶部