MENU

Linux 制作脚本,实现定时备份到腾讯云对象存储

• August 30, 2020 • Read: 1533 • 网站运维,经验教程

1、安装coscmd

pip install coscmd

2、编辑配置文件

vi ~/.cos.conf


[common]
secret_id = 123456789
secret_key = 987654321
bucket = backup-1234567890
region = ap-beijing
max_thread = 5
part_size = 1
schema = https
verify = md5
anonymous = False

3、编辑脚本文件

vi backup.sh
#!/bin/bash
# mysql 自动备份 压缩 保留7天
# 文件名为test_db+日期
backupDatabase1=www_thehill_cn
backupDatabase2=www_citypatient_

# 代表数据库名_年月日 也可以根据需要修改 %Y%m%d%H%M%S
database1fileName=${backupDatabase1}_`date +%Y%m%d%H%M%S`
database2fileName=${backupDatabase2}_`date +%Y%m%d%H%M%S`
site1fileName=www_thehill_cn_`date +%Y%m%d%H%M%S`
site2fileName=www_citypatient_com_`date +%Y%m%d%H%M%S`
# 存放备份的目录,可以是任意位置,先创建并赋权
baseDir=/www/backup/database/
siteDir=/www/backup/site/
site1fileDir=/www/wwwroot/www.thehill.cn/
site2fileDir=/www/wwwroot/www.citypatient.com/
domain1=www_zhangleilei_cn_
domian2=www_citypatient_com_

# 备份数据库
mysqldump --defaults-extra-file=/etc/my.cnf ${backupDatabase1} > ${baseDir}${database1fileName}.sql
mysqldump --defaults-extra-file=/etc/my.cnf ${backupDatabase2} > ${baseDir}${database2fileName}.sql
# 压缩 这个大写P用来兼容绝对路径
tar -zcPvf ${baseDir}${database1fileName}.sql.tar.gz ${baseDir}${database1fileName}.sql
tar -zcPvf ${baseDir}${database2fileName}.sql.tar.gz ${baseDir}${database2fileName}.sql
# 压缩网站文件
tar -zcPvf ${siteDir}${site1fileName}.tar.gz ${site1fileDir}
tar -zcPvf ${siteDir}${site2fileName}.tar.gz ${site2fileDir}
# 删除刚刚备份的sql文件,留下压缩的
rm -f ${baseDir}${database1fileName}.sql;
rm -f ${baseDir}${database2fileName}.sql;
# 备份文件夹到cos

coscmd upload -r ${baseDir} /backup/database/
coscmd upload -r ${siteDir} /backup/site/

# 删除7天前备份的数据,只保留一星期内的数据
 find ${baseDir} -mtime +7 -name "${backupDatabase1}*.tar.gz" -exec rm -rf {} \;
 find ${baseDir} -mtime +7 -name "${backupDatabase2}*.tar.gz" -exec rm -rf {} \;
 find ${siteDir} -mtime +7 -name "${domain1}*.tar.gz" -exec rm -rf {} \;
 find ${siteDir} -mtime +7 -name "${domain2}*.tar.gz" -exec rm -rf {} \;

4、在/etc/my.cnf中加上mysql的账户密码

vi /etc/my.cnf

5、在[client]下添加password/user/port/host

user = root
password = password
port = 3306
host = localhost

6、给脚本赋予执行权限

chmod 755 backup.sh

7、添加定时任务

crontab -e
# 在最后一行加这一句,意思是每天3点跑脚本
0 3 * * * /root/backup.sh
# 每隔三日3点执行脚本
0 3 */3 * * /root/backup.sh

8、重启一下corntab

service crond restart

Linux 制作脚本,实现定时备份到腾讯云对象存储 - 原文链接:https://blog.isww.cn/461.html

Last Modified: June 24, 2021
Archives QR Code Tip
QR Code for this page
Tipping QR Code
开往-友链接力