从远程mysql自动备份

从远程mysql自动备份

我每天都会备份存储我的在线网站内容的 mysql 数据库,并且我希望将这六个命令自动化为一个命令。

我尝试了一个简单的解决方案,只需将命令列表放入 Bash 脚本中。这会失败,因为脚本一旦进入远程主机就会停止。

任何帮助表示赞赏。

我失败的(bash脚本)尝试:

#! /bin/bash

  echo "Connecting to the remote host ...";
  ssh -p myport [email protected] ;
  echo "Making the backup on the remote host ...";
  mysqldump --databases --user=mysqluser --password=mypassword mydatabase > backup_copy.sql ;
  echo "Compressing the sql backup ...";
  gzip backup_copy.sql;
  echo "Leaving the remote host ...";
  exit;
  echo "Copying the backup from the remote host ...";
  scp -P myport [email protected]:backup_copy.sql.gz /my/location/to/store/backups ;
  echo "Task finished";

答案1

#!/bin/bash

# database credentials
DATABASEHOST="host"
DATABASEUSER="user"
DATABASEPASSWORD="password"
DATABASESCHEMA="database"
DATABASEENV="backup"

# Local directory of mysqldump file
LOCALDIR=/home/user/db-bkp

# Temporary directory for compressed file
TEMPDIR=/home/user/tmp

# Remote Directory for backups.
REMOTEDIR=/home/user/db-bkp

# Backup host to login to
BACKUPHOST="otherhost"
#--- end config

echo $(date +%H:%M)
echo "Creating the MySQL dump" 
mysqldump --host="$DATABASEHOST" --user="$DATABASEUSER" --password="$DATABASEPASSWORD" --single-transaction "$DATABASESCHEMA" > "$LOCALDIR"/"$(date +%Y%m%d)_bkp_$DATABASESCHEMA.sql"

#echo "Generating md5sum"
md5sum "$LOCALDIR"/* > "$LOCALDIR"/checklist.chk

#echo "Compressing the dump and checklist"
tar -cvzf "$TEMPDIR"/$(date +%Y%m%d)"_"$DATABASEENV"_"$DATABASESCHEMA".tar.gz" "$LOCALDIR"/*

#echo "Sending the compressed file to d2"
## scp "$TEMPDIR"/"$DATABASESCHEMA".tar.gz "$BACKUPHOST":"$REMOTEDIR"

#echo "Removing generated files"
#rm "$LOCALDIR"/checklist.chk > /dev/null 2>&1

#rm "$LOCALDIR"/"$(date +%Y%m%d)_bkp_$DATABASESCHEMA.sql" > /dev/null 2>&1

#rm "$TEMPDIR"/"$DATABASESCHEMA".tar.gz > /dev/null 2>&1

rm "$LOCALDIR"/"$(date +%Y%m%d)_bkp_$DATABASESCHEMA.sql"
echo $(date +%H:%M)

将 host,user,password,database,LOCALDIR,BACLUPHOST,REMOTEDIR 替换为您自己的参数

相关内容