python database backup and send email attachments

Record their own process of learning python

 

This is the backup, and send e-mail attachments stored function. Relatively simple, can modify, simplified steps, landscaping processes.

Sample code:

 

# ! / Usr / bin / env Python 
# - * - Coding: UTF-8 - * - 

Import os
 Import Time
 Import smtplib
 Import String
 from email.header Import Header
 from email.mime.multipart Import MimeMultipart
 from email.mime.text Import MimeText 

DEF the sendMail (DATAS):
     # define related data, replace their real data 
    the smtpserver = ' smtp.163.com ' 
    SENDER = ' [email protected] ' 
    # Receiver may be provided a plurality of use "," separated
    receiver = '[email protected]'
    username = '[email protected]'
    password = '123456'

    msg = MIMEMultipart()
    for i in datas:
        att = MIMEText(open(i, "rb").read(), "base64", "utf-8")
        att["Content-Type"] = "application/octet-stream"
        i = i.replace("/tmp/data_backup/", "")
        att["Content-Disposition"] = 'attachment; filename= %s ' %i
        msg.attach(att)

    receivers = receiver
    toclause = receivers.split(',')
    msg['To'] = ",".join(toclause)
    # 添加主题,不然提示554 DT:SPM错误
    msg['SUBJECT'] = "Database Backup successful " 

    # landing and send the message 
    the SMTP = smtplib.SMTP ()
     the try :
         # # turn on debug mode 
        # smtp.set_debuglevel (1) 
        smtp.connect (smtpserver) 
        smtp.login (username, password) 
        smtp.sendmail (SENDER, Receivers, msg.as_string ()) 
    the except :
         Print ( " mail transmission failed !! " )
     the else :
         Print ( " send success " )
     the finally : 
        smtp.quit () 


DEF the mysqldump (): 
    the USER = 'root'
    PASSWORD = '123456'
    MYSQLDUMP = 'docker exec -i  mysql mysqldump '
    DATABASES = ['yao','icaesee']
    TO_BACKUP_DIR="/tmp/data_backup/"
    lists = [];

    for  DB in  DATABASES:
        Backupfile_name = TO_BACKUP_DIR + DB +  '-' + time.strftime('%Y-%m-%d') + '.sql'
        Gzipfile_name = Backupfile_name + '.gz'
        if os.path.isfile(Gzipfile_name):
            print Gzipfile_name + " is already backup"
        else:
            Backup_command = MYSQLDUMP  + ' -u' +  USER  + ' -p' + PASSWORD  + " " +  DB  + ' >'  +  Backupfile_name
            print Backup_command
            # break
            if os.system(Backup_command) == 0:
                lists.append(Gzipfile_name)
            else:
                print "Fail"
            # 打包压缩成.gz
            GZIP_command = "gzip " +  Backupfile_name
            if os.system(GZIP_command) == 0:
                    print 'Successful gzip' + Backupfile_name +  ' to ' + Gzipfile_name
            else:
                    print 'Fail gzip' + Backupfile_name +  ' to ' + Gzipfile_name
    if len(lists) > 0:
        sendMail(lists)

mysqldump()

 

Guess you like

Origin www.cnblogs.com/todarcy/p/11059331.html