LoginSignup
2
6

More than 5 years have passed since last update.

cronとrsyncでDBdumpファイルを自動バックアップ

Posted at

DBバックアップをとるためにcronでmysqldumpを回したりしますが、
そもそもサーバーが落ちるとバックアップの甲斐がないわけです。
そこで、別のサーバーに転送しておこうというお話。

スクリプト

#!/bin/sh

# バックアップファイルを何日分残しておくか
period=7
# バックアップファイルを保存するディレクトリ
dirpath='/home/hoge/backup/'
# バックアップ用別サーバー情報(開発環境)
remotehost='fugafuga'
remotedir='fuga_backup/'
remoteuser='fugauser'
remotepass='fugapass'

# ファイル名を定義(※ファイル名で日付がわかるようにしておきます)
filename=`date +%y%m%d`

# mysqldump実行
mysqldump --opt --password=hogepass hogedb > $dirpath/$filename.sql

# パーミッション変更
chmod 700 $dirpath/$filename.sql

# 古いバックアップファイルを削除
oldfile=`date --date "$period days ago" +%y%m%d`
rm -f $dirpath/$oldfile.sql

# 別サーバーに同期
expect -c "
set timeout 3600
spawn rsync -av -e ssh --delete $dirpath $remoteuser@$remotehost:$remotedir
expect {
        \"Are you sure you want to continue connecting (yes/no)?\" {
                send \"yes\r\"
                expect {
                        -re \".*password:.*\" {
                                send \"$remotepass\r\"
                        }
                }
        }
        -re \".*password:.*\" {
            send \"$remotepass\r\"
        }
}
expect {
  \"denied\" { exit 1 }
  eof { exit 0 }
}
interact
"

パスワードをベタで書いているのは微妙ですが…

◆ 参考
rsyncで自動バックアップ(Linux)

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6