MYSQL定期备份是一项重要的工作,但人工操作太繁琐,也难避免有所疏漏,本文主要讲述利用crontab定时备份mysql至本机,以及利用rsync同步数据到异机,从而达到异机定时备份。

mysql定时备份篇

1、创建备份文件夹
#mkdir -p /u01/bak/mysqldata
2、编写运行脚本
#vim /usr/sbin/bakmysql.sh

代码:
#!/bin/bash
# Name:bakmysql.sh
# This is a ShellScript For Auto DB Backup and Delete old Backup
#
backupdir=/u01/bak/mysqldata
time=` date +%Y%m%d%H `
/usr/bin/mysqldump -u root -ppassword dataname  > $backupdir/name1$time.sql
/usr/bin/mysqldump -u root -ppassword dataname  > $backupdir/name2$time.sql
/usr/bin/mysqldump -u root -ppassword dataname > $backupdir/name3$time.sql
#
find $backupdir -name "*.sql" -type f -mtime +5 -exec rm {} \; > /dev/null 2>&1
注:删除5天前备份文件
3、为脚本添加执行权限
# chmod +x /usr/sbin/bakmysql.sh
4、修改/etc/crontab
58 23 * * * root /usr/sbin/bakmysql.sh

注:每晚23:58执行一次自动备份
5、重启crontab
# /etc/rc.d/init.d/crond restart
6、恢复数据备份文件
#mysql -u root -p dataname < name2008010103.sql

异机同步篇(使用rsync算法)

1、配置hosts(主机、备机)
#vim /etc/hosts
IP1     hostname1
IP2     hostname2

2、安装rsync(主机、备机)

#yum install rsync

3、 配置rsync服务器

#vim /etc/rsyncd.conf

uid = root

gid = root

max connections = 200

timeout = 600

use chroot = no

read only = no

port = 873

log file=/var/log/rsyncd.log

pid file=/var/run/rsyncd.pid

lock file=/var/run/rsyncd.lock

[test]

path=/u01/bak/mysqldata

comment=backup test

ignore errors

hosts allow=IP2

auth user=test

secrets file=/root/rsync.passwd

#vim /root/rsync.passwd

test 123456

#chown root:root /root/rsync.passwd

#chmod 600 /root/rsync.passwd

4、 配置rsync客户端

#vim /etc/rsyncd.conf

uid = root

gid = root

max connections = 200

timeout = 600

use chroot = no

read only = no

port = 873

log file=/var/log/rsyncd.log

pid file=/var/run/rsyncd.pid

lock file=/var/run/rsyncd.lock

[test]

path=/home

comment=backup test

ignore errors

hosts allow=IP1

auth user=test

secrets file=/root/rsync.passwd

#vim /root/rsync.passwd

123456

#chown root:root/root/rsync.passwd

#chmod 600 /root/rsync.passwd

5、启动rsync服务(主机、备机)

#/usr/bin/rsync --daemon

#netstat -an | grep 873

注:开机启动如下

#vim /etc/rc.d/rc.local

/usr/bin/rsync --daemon

6、编写定时同步脚本

#vim /etc/rsync.sh
代码:

#!/bin/bash
#Name:rsync.sh
#This is a ShellScript For Data synchronization
rsync -vrtopg --progress --delete root@IP1::test/ /home --password-file=/root/rsync.passwd

7、设置定时执行

#chmod +x /etc/rsync.sh

#vim /etc/crontab

58 23 * * * root /etc/rsync.sh

8、重启crontab
# /etc/rc.d/init.d/crond restart

至此mysql异机定时备份完成,建议一周内须查看备份效果,以及测试mysql备份可用性。

扩展阅读(网络参考资料,以下资料归属网络作者,请注重“版权”):

http://www.howtocn.org/rsync:use_rsync_server                          使用 rsync 服务

http://colderboy.blog.51cto.com/485582/132054/                         rsync参数详解、利用ssh、rsync 实现数据的定时同步