2007年1月26日 星期五

[Linux] 製作每日自動備份的方法 !

在Linux上, 如何每日做自動備份, 我做法如下 :

1.首先寫幾支shell script, 如下 :
  • 備份網頁 : html_backup.sh
    #!/bin/bash

    BACKUPDIR=/opt/backup/www/html
    LOGDIR=/opt/backup/log

    echo "[網頁備份錯誤訊息] : " `date +%F` > $LOGDIR/html_backup_err.log

    cd $BACKUPDIR
    days=7
    for ((i=$days-1 ; i>=1 ; i=i-1))
    do
    declare -i j=$i-1
    mv html_$j.tar.bz2 html_$i.tar.bz2 2>> $LOGDIR/html_backup_err.log
    done


    cd /var

    tar jcf $BACKUPDIR/html_0.tar.bz2 www 2>> $LOGDIR/html_backup_err.log
  • 備份PostgreSQL資料庫 : pgsql_backup.sh
    #!/bin/bash

    BACKUPDIR=/opt/backup/www/pgsql
    LOGDIR=/opt/backup/log

    echo "[資料庫備份錯誤訊息] : " `date +%F` > $LOGDIR/pgsql_backup_err.log

    cd $BACKUPDIR
    days=7
    for ((i=$days-1 ; i>=1 ; i=i-1))
    do
    declare -i j=$i-1
    mv pgsql_$j.sql.gz pgsql_$i.sql.gz 2>> $LOGDIR/pgsql_backup_err.log
    done

    cd $BACKUPDIR

    pg_dump -U postgres webdb > pgsql_0.sql 2>> $LOGDIR/pgsql_backup_err.log
    gzip pgsql_0.sql 2>> $LOGDIR/pgsql_backup_err.log
  • 備份系統設定檔 : etc_backup.sh
    #!/bin/bash

    BACKUPDIR=/opt/backup/www/etc
    LOGDIR=/opt/backup/log
    echo "[系統參數備份錯誤訊息] : " `date +%F` > $LOGDIR/etc_backup_err.log

    cd $BACKUPDIR
    days=7
    for ((i=$days-1 ; i>=1 ; i=i-1))
    do
    declare -i j=$i-1
    mv etc_$j.tar.bz2 etc_$i.tar.bz2 2>> $LOGDIR/etc_backup_err.log
    done

    cd /

    tar jcf $BACKUPDIR/etc_0.tar.bz2 etc 2>> $LOGDIR/etc_backup_err.log
  • 自動email通知系統狀況 : email_notify.sh
    #!/bin/bash
    MAIL_MESSAGE="/tmp/mail.msg"
    MAIL_ADDRESS="your_email@your_email_server"
    MAIL_CC="your_email2@your_email_server2"
    CURRENT_DATE=`date +%F`
    MY_HOSTNAME=`hostname`

    # uptime & load average
    echo -e "\n[開機時間和平均負載]" > $MAIL_MESSAGE
    uptime >> $MAIL_MESSAGE

    # disk space
    echo -e "\n[磁碟容量]" >> $MAIL_MESSAGE
    df -k >> $MAIL_MESSAGE

    # recently login
    echo -e "\n[最近登入]" >> $MAIL_MESSAGE
    last >> $MAIL_MESSAGE

    # data backup error log
    LOGDIR=/opt/backup/log
    echo -e "\n" >> $MAIL_MESSAGE
    cat $LOGDIR/cge_etc_backup_err.log >> $MAIL_MESSAGE
    cat $LOGDIR/cge_html_backup_err.log >> $MAIL_MESSAGE
    cat $LOGDIR/cge_pgsql_backup_err.log >> $MAIL_MESSAGE
    cat $LOGDIR/TypeBackup_err.log >> $MAIL_MESSAGE

    # send it
    cat $MAIL_MESSAGE | mail -s "$MY_HOSTNAME : ${CURRENT_DATE} 系統狀況回報 !" -c $
    MAIL_CC $MAIL_ADDRESS

    #clean up
    rm $MAIL_MESSAGE
2.每日自動執行
  • crontab -u root -e
    00 01 * * * /opt/backup/bin/etc_backup.sh
    30 01 * * * /opt/backup/bin/pgsql_backup.sh
    00 02 * * * /opt/backup/bin/html_backup.sh
    00 07 * * * /opt/backup/bin/email_notify.sh
3.如此一來, 系統便會自動每日晚上01:00 ~ 07:00備份資料, 並將結果email通知您
4.注意 : 最好再加上每日將資料上傳到另一台ftp主機, 或備份到磁帶中 !

0 意見: