shell自動(dòng)備份mysql腳本

作用

定時(shí)執(zhí)行mysql全量備份,并上傳到備用服務(wù)器。使用mysqldump備份mysql,scp上傳文件到備份服務(wù)器。

腳本實(shí)現(xiàn)

#!/usr/bin/env bash

#保存?zhèn)浞輦€(gè)數(shù),備份31天數(shù)據(jù)
number=31
#備份保存路徑
backup_dir=/Users/xxUser/Downloads
#日期
dd=`date +%Y-%m-%d-%H-%M-%S`
#備份工具
tool=mysqldump
#數(shù)據(jù)庫用戶名
username=root
#數(shù)據(jù)庫密碼
password=63791
#數(shù)據(jù)庫地址
hostname=127.0.0.1
# 備份文件上傳ip
upload_hostname=28.71.32.33
# 備份服務(wù)器用戶名
upload_username=root
# 備份服務(wù)器密碼
upload_password=xxxpwd
# 備份文件上傳地址
upload_dir=/root/xxUser/tmp
#將要備份的數(shù)據(jù)庫
database_names=(
  ims_message
  ims_onduty
  ims_info
)

#如果文件夾不存在則創(chuàng)建
if [ ! -d $backup_dir ];
then
    mkdir -p $backup_dir;
fi

tmp_dir=tmp_dir

mkdir -p $backup_dir/$tmp_dir;

# 備份數(shù)據(jù)庫,并寫入日志
backupDb(){
  # 開始備份
  $tool --column-statistics=0 -h$hostname -u$username -p$password $1 > $backup_dir/$tmp_dir/$1-$dd.sql
  # 寫創(chuàng)建備份日志
  echo "create $backup_dir/$1-$dd.dupm" >> $backup_dir/log.txt
}

# 循環(huán)備份
for value in "${database_names[@]}"
do
  backupDb $value
done

# 壓縮所有備份sql
zip -j $backup_dir/mysql_backup_$dd.zip $backup_dir/$tmp_dir/*.sql

# 刪除臨時(shí)文件夾

rm -rf $backup_dir/$tmp_dir

uploadFile(){
/usr/bin/expect << EOF
set timeout 300
spawn scp $backup_dir/mysql_backup_$dd.zip $upload_username@$upload_hostname:$upload_dir
expect {
  "(yes/no)?" { send "yes\r" ; exp_continue }
  "Password:" { send "$upload_password\r" }
}
expect eof
EOF
}

# 嘗試上傳文件到備份服務(wù)器
if [ -n "$upload_password" ]
then
  uploadFile
fi

#找出需要?jiǎng)h除的備份
delfile=`ls -l -crt  $backup_dir/*.zip | awk '{print $9 }' | head -1`

#判斷現(xiàn)在的備份數(shù)量是否大于$number
count=`ls -l -crt  $backup_dir/*.zip | awk '{print $9 }' | wc -l`

if [ $count -gt $number ]
then
  #刪除最早生成的備份,只保留number數(shù)量的備份
  rm $delfile
  #寫刪除文件日志
  echo "delete $delfile" >> $backup_dir/log.txt
fi

加入定時(shí)任務(wù)

  • 新建腳本
[root@root test]# touch autoBackup.sh
[root@root test]# vim autoBackup.sh
  • 把上面的腳本拷貝進(jìn)去,并給腳本賦予執(zhí)行權(quán)限
[root@root test]# chmod +x autoBackup.sh
[root@root test]# crontab -e
01 */24 * * * sh /path/to/autoBackup.sh
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容