Ubuntu 上备份 MySQL 的Shell脚本

Ubuntu Linux Backup MySQL Server Shell Script

转自

http://www.cyberciti.biz/faq/ubuntu-linux-mysql-nas-ftp-backup-script/


Q. I’m new to Linux and I’ve dedicated VPS server running Ubuntu Linux. I’m using CMS software and MySQL act as database server. Can you explain how can I backup all mysql server databases to ftp server IP address called 10.1.5.2?

A. You can use mysqldump command to backup database. The mysqldump client is a backup program. It can be used to dump a database or a collection of databases for backup or for transferring the data to another SQL server. The dump contains SQL statements to create the table or populate it, or both.

Once database is dumped, you need to upload the same to ftp server. Use lftp client to upload all files.

Install lftp

lftp is a file transfer program that allows sophisticated ftp, http and other connections to other hosts. If site is specified then lftp will connect to that site otherwise a connection has to be established with the open command. To install lftp, enter:

sudo apt-get install lftp

Shell script to backup MySQL database server

Following is the shell script. It will dump all database to /backup/mysql and later it will upload to FTP server. You need to setup correct username and password before using the script:

 

#!/bin/bash

### MySQL Server Login Info ###

MUSER="root"

MPASS="MYSQL-ROOT-PASSWORD"

MHOST="localhost"

MYSQL="$(which mysql)"

MYSQLDUMP="$(which mysqldump)"

BAK="/backup/mysql"

GZIP="$(which gzip)"

### FTP SERVER Login info ###

FTPU="FTP-SERVER-USER-NAME"

FTPP="FTP-SERVER-PASSWORD"

FTPS="FTP-SERVER-IP-ADDRESS"

NOW=$(date +"%d-%m-%Y")

 

### See comments below ###

### [ ! -d $BAK ] && mkdir -p $BAK || /bin/rm -f $BAK/* ###

[ ! -d "$BAK" ] && mkdir -p "$BAK"

 

DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"

for db in $DBS

do

 FILE=$BAK/$db.$NOW-$(date +"%T").gz

 $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS $db | $GZIP -9 > $FILE

done

 

lftp -u $FTPU,$FTPP -e "mkdir /mysql/$NOW;cd /mysql/$NOW; mput /backup/mysql/*; quit" $FTPS

Save script as /home/your-name/mysql.backup.sh file. Setup executable permission:

$ chmod +x /home/your-name/mysql.backup.sh


To backup MySQL, enter:

/home/your-name/mysql.backup.sh


OR

sudo /home/your-name/mysql.backup.sh

Run MySQL backup script as cron job

To automate procedure setup a cron job. For example run backup everyday at midnight (i.e once a day), enter:

$ sudo crontab -e


Append following cron job:

@midnight /home/you/mysql.backup.sh >/dev/null 2>&1


Save and close the file. Please note that above script should work with other Linux distros or UNIX like oses.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值