使用Shell脚本实现网站文件和MySQL数据库的自动备份

我们的网站服务器操作系统是CentOS,网站整体备份需要备份网站文件和数据库两个部分,网站文件的备份使用tar打包压缩,MySQL数据库备份使用mysqldump进行。

一、备份网站文件

备份网站文件很简单,直接用tar命令即可。

[root@localhost www]# tar zcf xieyincai-$(date +%Y%m%d).tar.gz xieyincai
[root@localhost www]# ll
drwxr-xr-x 13 root root     4096 Mar 18  2015 xieyincai
-rw-r--r--  1 root root 44814361 Aug 12 12:56 xieyincai-20180812.tar.gz

如果觉得压缩文件太大,那么我们可以用split命令分割。

[root@localhost www]# tar zcf - xieyincai | split -b 16m - xieyincai-$(date +%Y%m%d).tar.gz.
[root@localhost www]# ll
drwxr-xr-x 13 root root     4096 Mar 18  2015 xieyincai
-rw-r--r--  1 root root 44814361 Aug 12 12:56 xieyincai-20180812.tar.gz
-rw-r--r--  1 root root 16777216 Aug 12 13:00 xieyincai-20180812.tar.gz.aa
-rw-r--r--  1 root root 16777216 Aug 12 13:00 xieyincai-20180812.tar.gz.ab
-rw-r--r--  1 root root 11259929 Aug 12 13:00 xieyincai-20180812.tar.gz.ac

二、备份MySQL数据库

MySQL数据库备份使用mysqldump进行,具体操作如下:

[root@localhost backup]# mysqldump -uroot -pbeijing xieyincai | gzip > xieyincai-$(date +%Y%m%d).sql.gz
[root@localhost backup]# ll
-rw-r--r-- 1 root root 1786968 Aug 12 12:33 xieyincai-20180812.sql.gz

如果觉得压缩文件太大,那么我们可以用split命令分割。

[root@localhost backup]# mysqldump -uroot -pbeijing xieyincai | gzip | split -b 512k - xieyincai-$(date +%Y%m%d).sql.gz.
[root@localhost backup]# ll
-rw-r--r-- 1 root root 1786968 Aug 12 12:33 xieyincai-20180812.sql.gz
-rw-r--r-- 1 root root  524288 Aug 12 12:34 xieyincai-20180812.sql.gz.aa
-rw-r--r-- 1 root root  524288 Aug 12 12:34 xieyincai-20180812.sql.gz.ab
-rw-r--r-- 1 root root  524288 Aug 12 12:34 xieyincai-20180812.sql.gz.ac
-rw-r--r-- 1 root root  214104 Aug 12 12:34 xieyincai-20180812.sql.gz.ad

三、简单Shell脚本

#!/bin/bash

#备份网站文件
cd /home/www
tar zcf - xieyincai | split -b 16m - xieyincai-$(date +%Y%m%d).tar.gz.
mv xieyincai-$(date +%Y%m%d).tar.gz.* /home/backup

#备份MySQL数据库
cd /home/backup
mysqldump -uroot -pbeijing xieyincai | gzip | split -b 512k - xieyincai-$(date +%Y%m%d).sql.gz.
[root@localhost ~]# ./backup.sh
[root@localhost ~]# ll /home/backup
-rw-r--r-- 1 root root   524288 Aug 12 13:38 xieyincai-20180812.sql.gz.aa
-rw-r--r-- 1 root root   524288 Aug 12 13:38 xieyincai-20180812.sql.gz.ab
-rw-r--r-- 1 root root   524288 Aug 12 13:38 xieyincai-20180812.sql.gz.ac
-rw-r--r-- 1 root root   214105 Aug 12 13:38 xieyincai-20180812.sql.gz.ad
-rw-r--r-- 1 root root 16777216 Aug 12 13:38 xieyincai-20180812.tar.gz.aa
-rw-r--r-- 1 root root 16777216 Aug 12 13:38 xieyincai-20180812.tar.gz.ab
-rw-r--r-- 1 root root 11259929 Aug 12 13:38 xieyincai-20180812.tar.gz.ac

如果想要自动定时运行,可以把这个backup.sh添加到crontab中即可~

1 thought on “使用Shell脚本实现网站文件和MySQL数据库的自动备份

Leave a Reply

Your email address will not be published. Required fields are marked *