linux下使用python3发送邮件定时备份数据库脚本

网友投稿 1346 2022-10-19

linux下使用python3发送邮件定时备份数据库脚本

linux下使用python3发送邮件定时备份数据库脚本

网站搭建完成后数据尤其重要,如下是整理的定时备份数据库并将数据库自动发送到我的另一个邮箱做备份,这样就相对安全多了

python3发送邮件脚本

vim /data/backup/script/send_email.py#!/usr/bin/python3import smtplibfrom email.header import Headerfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport sysimport osif len(sys.argv) == 1: print('请输入标题与附件') sys.exit()sender = 'h3blog***@163.com'receiver = '46*****14@qq.com'smtpserver = 'smtp.163.com'username = 'h3blog***'password = '123456***'mail_title = sys.argv[1]# 创建一个带附件的实例message = MIMEMultipart()message['From'] = sendermessage['To'] = receivermessage['Subject'] = Header(mail_title, 'utf-8')# 邮件正文内容message.attach(MIMEText('备份服务器数据', 'plain', 'utf-8'))for att in sys.argv[2:]: # 构造附件1(附件为TXT格式的文本) name = os.path.basename(att) att1 = MIMEText(open(att, 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename="{}"'.format(name) message.attach(att1)smtpObj = smtplib.SMTP_SSL() # 注意:如果遇到发送失败的情况(提示远程主机拒接连接),这里要使用SMTP_SSL方法smtpObj.connect(smtpserver)smtpObj.login(username, password)smtpObj.sendmail(sender, receiver, message.as_string())print("邮件发送成功!!!")smtpObj.quit()

该脚本可独立运行

./send_email.py 测试 /tmp/test.txt

shell脚本备份数据脚本

vim /data/backup/script/backupmysql.sh#!/bin/bash# Name:bakmysql.sh#backupdir=/data/backup/databasetime=` date +%Y%m%d%H%M%S `mysqldump -u root -p4232*** h3blog | gzip > $backupdir/h3blog_$time.sql.gz#find $backupdir -name "h3blog_*.sql.gz" -type f -mtime +7 -exec rm {} \; > /dev/null 2>&1/data/backup/script/send_email.py bakup_mysql $backupdir/h3blog_$time.sql.gz

编辑cron定时任务

crontab -e# Edit this file to introduce tasks to be run by cron.## Each task to run has to be defined through a single line# indicating with different fields when the task will be run# and what command to run for the task## To define the time you can provide concrete values for# minute (m), hour (h), day of month (dom), month (mon),# and day of week (dow) or use '*' in these fields (for 'any').## Notice that tasks will be started based on the cron's system# daemon's notion of time and timezones.## Output of the crontab jobs (including errors) is sent through# email to the user the crontab file belongs to (unless redirected).## For example, you can run a backup of all your user accounts# at 5 a.m every week with:# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/## For more information see the manual pages of crontab(5) and cron(8)## m h dom mon dow command0 1

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:swoole 分布式通讯框架
下一篇:You-Get 就是这么强势!
相关文章

 发表评论

暂时没有评论,来抢沙发吧~