将MySQL数据库备份到远程服务器

时间:2013-12-29 18:47:59

标签: mysql database cron backup

我需要使用Cron自动将我的MySQL数据库备份到我的网站根目录下的文件夹中。

我搜索它并最终作为下面的cron工作达到了一个点。

0 1 * * * /usr/bin/mysqldump --opt --all-databases -u USERNAME -pPASSWORD | gzip > /backup-folder/db_bckp`date +\%Y-\%m-\%d`.sql.gz

然而,没有任何反应。

可能是什么原因?

1 个答案:

答案 0 :(得分:0)

我会让cron执行这个.sh文件。确保在外部服务器上验证您的公共ssh密钥...

#!/bin/bash
## List of databases to backup
 declare -a arr=(database1 database2)
 ##use something like this to get full list of databases to loop through
 #databases=`mysql -B -r -u ${user} --skip-column-names -p${pass} --execute='show databases'`
## mysql user should have SELECT and LOCK privileges on tables to backup
 user='you'
 pass='pass'

## scp remote variables
 url_ext='external url' 
 folder_ext='/'
 use_ext='external user'
 pass_ext='external password'

## base dir where backups are saved
 shdir='/home/to/folder/'

## date and hostname
 day=$(date | awk '{ print $2"-"$3"-"$6}')
 hostname=$(hostname)  

## now loop through the above array
 for i in ${arr[@]}
 do
 echo $i # current database
 mysqldump -u $user --password=$pass $i > "$i.sql" #dump db to file
 wait

#if you want you can zip the files
 zip backup_db_$i_$day.zip "$i.sql" 
#or tar them
#tar -zcvf backup_db_$i_$day.tar.gz /route/to/file
 wait

 ##2 using scp you can send the backups to external server
 ##read about private and public ssh keys for automation without password
 scp -v backup_db_$i_$day.zip  user@ip:/home/to/backup/folder/

 wait
 done

 #Errase old backups
 rm -rf $shdir*.sql