用于数据库备份的Linux shell脚本

时间:2013-10-29 17:14:03

标签: mysql linux shell cron

我尝试了许多用于数据库备份的脚本,但我无法做到。我想每小时备份一次我的数据库 我将文件添加到" /etc/cron.hourly /"文件夹,将其chmod更改为755,但它没有运行。 至少我写了我的伪代码。

如果您能为此操作编写脚本并告诉我应该怎么做,我会很高兴的? 将此脚本文件添加到/etc/cron.hourly/文件夹后。

  • 获取当前日期并创建变量date=date(d_m_y_H_M_S)
  • 为文件名filename="$date".gz
  • 创建变量
  • mysqldump --user=my_user --password=my_pass --default-character-set=utf8 my_database | gzip > "/var/www/vhosts/system/example.com/httpdocs/backups/$("filename")
  • 一样获取我的数据库转储
  • 删除文件夹/var/www/vhosts/system/example.com/httpdocs/backups/中超过8天的所有文件
  • 对于文件"/var/www/vhosts/system/example.com/httpdocs/backup_log.txt",此文本将写为:Backup is created at $("date")
  • 将文件所有者(chown)从root更改为" my_user"。因为我想从" my_user"中打开备份和日志文件。 FTP帐户。
  • 我不想在每个cron之后发送电子邮件。将添加>/dev/null 2>&1

10 个答案:

答案 0 :(得分:92)

经过数小时和数小时的工作,我创建了一个如下所示的解决方案。我为其他可以受益的人复制粘贴。

首先创建一个脚本文件并授予此文件可执行权限。

# cd /etc/cron.daily/
# touch /etc/cron.daily/dbbackup-daily.sh
# chmod 755 /etc/cron.daily/dbbackup-daily.sh
# vi /etc/cron.daily/dbbackup-daily.sh

然后使用Shift + Ins

将以下行复制到文件中
#!/bin/sh
now="$(date +'%d_%m_%Y_%H_%M_%S')"
filename="db_backup_$now".gz
backupfolder="/var/www/vhosts/example.com/httpdocs/backups"
fullpathbackupfile="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt
echo "mysqldump started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --user=mydbuser --password=mypass --default-character-set=utf8 mydatabase | gzip > "$fullpathbackupfile"
echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
chown myuser "$fullpathbackupfile"
chown myuser "$logfile"
echo "file permission changed" >> "$logfile"
find "$backupfolder" -name db_backup_* -mtime +8 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0

编辑:
如果使用InnoDB并且备份需要花费太多时间,则可以添加“single-transaction”参数以防止锁定。所以mysqldump行将是这样的:

mysqldump --user=mydbuser --password=mypass --default-character-set=utf8
          --single-transaction mydatabase | gzip > "$fullpathbackupfile"

答案 1 :(得分:30)

创建一个类似于此的脚本:

#!/bin/sh -e

location=~/`date +%Y%m%d_%H%M%S`.db

mysqldump -u root --password=<your password> database_name > $location

gzip $location

然后,您可以编辑脚本将要运行的用户的crontab

$> crontab -e

并附上条目

01 * * * * ~/script_path.sh

这将使它在每天每小时的第一分钟运行。

然后你只需添加你的卷和其他功能,你就可以了。

答案 2 :(得分:7)

我遇到了同样的问题。 但我设法编写一个脚本。 希望这会有所帮助。

#!/bin/bash
# Database credentials
user="username"
password="password"
host="localhost"
db_name="dbname"
# Other options
backup_path="/DB/DB_Backup"
date=$(date +"%d-%b-%Y")
# Set default file permissions
umask 177
# Dump database into SQL file
mysqldump --user=$user --password=$password --host=$host $db_name >$backup_path/$db_name-$date.sql

# Delete files older than 30 days
find $backup_path/* -mtime +30 -exec rm {} \;


#DB backup log
echo -e "$(date +'%d-%b-%y  %r '):ALERT:Database has been Backuped"    >>/var/log/DB_Backup.log

答案 3 :(得分:2)

#!/bin/sh
#Procedures = For DB Backup
#Scheduled at : Every Day 22:00

v_path=/etc/database_jobs/db_backup
logfile_path=/etc/database_jobs
v_file_name=DB_Production
v_cnt=0

MAILTO="abc@as.in"
touch "$logfile_path/kaka_db_log.log"

#DB Backup
mysqldump -uusername -ppassword -h111.111.111.111 ddbname > $v_path/$v_file_name`date +%Y-%m-%d`.sql 
if [ "$?" -eq 0 ]
  then
   v_cnt=`expr $v_cnt + 1`
  mail -s "DB Backup has been done successfully" $MAILTO < $logfile_path/db_log.log
 else
   mail -s "Alert : kaka DB Backup has been failed" $MAILTO < $logfile_path/db_log.log
   exit
fi

答案 4 :(得分:1)

这是我的ubuntu的mysql备份脚本,以防它对某人有所帮助。

#Mysql back up script

start_time="$(date -u +%s)"

now(){
date +%d-%B-%Y_%H-%M-%S
}

ip(){
/sbin/ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'
}

filename="`now`".zip
backupfolder=/path/to/any/folder
fullpathbackupfile=$backupfolder/$filename
db_user=xxx
db_password=xxx
db_name=xxx

printf "\n\n"
printf "******************************\n"
printf "Started Automatic Mysql Backup\n"
printf "******************************\n"
printf "TIME: `now`\n"
printf "IP_ADDRESS: `ip` \n"
printf "DB_SERVER_NAME: DB-SERVER-1\n"

printf "%sBACKUP_FILE_PATH $fullpathbackupfile\n"

printf "Starting Mysql Dump \n"

mysqldump -u $db_user -p$db_password $db_name| pv | zip > $fullpathbackupfile

end_time="$(date -u +%s)"

elapsed=$(($end_time-$start_time))

printf "%sMysql Dump Completed In $elapsed seconds\n"

printf "******************************\n"

PS:记住要在ubuntu中安装pv和zip

sudo apt install pv
sudo apt install zip

这是我通过在Ubuntu上使用crontab -e每6小时运行一次来​​设置crontab的方法

0 */6 * * * sh /path/to/shfile/backup-mysql.sh >> /path/to/logs/backup-mysql.log 2>&1

很酷的事情是它将创建一个zip文件,该文件更容易从任何地方解压缩

答案 5 :(得分:0)

#!/bin/bash

# Add your backup dir location, password, mysql location and mysqldump        location
DATE=$(date +%d-%m-%Y)
BACKUP_DIR="/var/www/back"
MYSQL_USER="root"
MYSQL_PASSWORD=""
MYSQL='/usr/bin/mysql'
MYSQLDUMP='/usr/bin/mysqldump'
DB='demo'

#to empty the backup directory and delete all previous backups
rm -r $BACKUP_DIR/*  

mysqldump -u root -p'' demo | gzip -9 > $BACKUP_DIR/demo$date_format.sql.$DATE.gz

#changing permissions of directory 
chmod -R 777 $BACKUP_DIR

答案 6 :(得分:0)

你可能会考虑这个开源工具,matiri,https://github.com/AAFC-MBB/matiri这是一个带有Sqlite3元数据的并发mysql备份脚本。特性:

  • 多服务器:支持多个MySQL服务器,无论它们是否位于相同或不同的物理服务器上。
  • 并行:要备份的服务器上的每个数据库都是单独完成的,并行完成(并发可设置:默认值:3)
  • 压缩:压缩每个数据库备份
  • Checksummed:存储的每个压缩备份文件的SHA256和所有文件的存档
  • 已存档:所有数据库备份都合并为单个文件
  • 记录:存储在Sqlite3数据库中的备份信息

完全披露:原始的matiri作者。

答案 7 :(得分:0)

作为DBA,您必须安排MySQL数据库的备份,以防出现任何问题,以便可以从当前备份中恢复数据库。

在这里,我们使用mysqldump备份mysql数据库,并且可以将其放入脚本中。

[orahow @ oradbdb DB_Backup] $ cat .backup_script.sh

#!/bin/bash
# Database credentials
user="root"
password="1Loginxx"
db_name="orahowdb"
v_cnt=0
logfile_path=/DB_Backup
touch "$logfile_path/orahowdb_backup.log"
# Other options
backup_path="/DB_Backup"
date=$(date +"%d-%b-%Y-%H-%M-%p")
# Set default file permissions

继续阅读...。 MySQL Backup

答案 8 :(得分:0)

我已经准备了一个Shell脚本来创建MYSQL数据库的备份。 您可以使用它,以便我们备份数据库。

    #!/bin/bash
    export PATH=/bin:/usr/bin:/usr/local/bin
    TODAY=`date +"%d%b%Y_%I:%M:%S%p"`

    ################################################################
    ################## Update below values  ########################
    DB_BACKUP_PATH='/backup/dbbackup'
    MYSQL_HOST='localhost'
    MYSQL_PORT='3306'
    MYSQL_USER='auriga'
    MYSQL_PASSWORD='auriga@123'
    DATABASE_NAME=( Project_O2 o2)
    BACKUP_RETAIN_DAYS=30   ## Number of days to keep local backup copy; Enable script code in end of th script

    #################################################################
    { mkdir -p ${DB_BACKUP_PATH}/${TODAY}
        echo "
                                ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
    } || {
        echo "Can not make Directry"
        echo "Possibly Path is wrong"
    }
    { if ! mysql -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e 'exit'; then
        echo 'Failed! You may have Incorrect PASSWORD/USER ' >> ${DB_BACKUP_PATH}/Backup-Report.txt
        exit 1
    fi

        for DB in "${DATABASE_NAME[@]}"; do
            if ! mysql -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e "use "${DB}; then
                echo "Failed! Database ${DB} Not Found on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt

            else
                # echo "Backup started for database - ${DB}"            
                # mysqldump -h localhost -P 3306 -u auriga -pauriga@123 Project_O2      # use gzip..

                mysqldump -h ${MYSQL_HOST} -P ${MYSQL_PORT} -u ${MYSQL_USER} -p${MYSQL_PASSWORD} \
                          --databases ${DB} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DB}-${TODAY}.sql.gz

                if [ $? -eq 0 ]; then
                    touch ${DB_BACKUP_PATH}/Backup-Report.txt
                    echo "successfully backed-up of ${DB} on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
                    # echo "Database backup successfully completed"

                else
                    touch ${DB_BACKUP_PATH}/Backup-Report.txt
                    echo "Failed to backup of ${DB} on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
                    # echo "Error found during backup"
                    exit 1
                fi
            fi
        done
    } || {
        echo "Failed during backup"
        echo "Failed to backup on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
        # ./myshellsc.sh 2> ${DB_BACKUP_PATH}/Backup-Report.txt
    }

    ##### Remove backups older than {BACKUP_RETAIN_DAYS} days  #####

    # DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`

    # if [ ! -z ${DB_BACKUP_PATH} ]; then
    #       cd ${DB_BACKUP_PATH}
    #       if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
    #             rm -rf ${DBDELDATE}
    #       fi
    # fi

    ### End of script ####

在脚本中,我们只需要提供用户名,密码,数据库名称(或多个数据库,如果多个),以及端口号(如果不同)。

要运行脚本,请使用Command作为:

sudo ./script.sc

我还建议您是否要在类似以下文件的文件中查看结果: 发生故障或备份成功, 然后使用以下命令:

sudo ./myshellsc.sh 2>> Backup-Report.log

谢谢。

答案 9 :(得分:0)

现在,将以下内容复制到脚本文件中(例如:/backup/mysql-backup.sh),然后保存在Linux系统上。

    #!/bin/bash

    export PATH=/bin:/usr/bin:/usr/local/bin
    TODAY=`date +"%d%b%Y"`

    DB_BACKUP_PATH='/backup/dbbackup'
    MYSQL_HOST='localhost'
    MYSQL_PORT='3306'
    MYSQL_USER='root'
    MYSQL_PASSWORD='mysecret'
    DATABASE_NAME='mydb'
    BACKUP_RETAIN_DAYS=30   

    mkdir -p ${DB_BACKUP_PATH}/${TODAY}
    echo "Backup started for database - ${DATABASE_NAME}"

    mysqldump -h ${MYSQL_HOST} \
   -P ${MYSQL_PORT} \
   -u ${MYSQL_USER} \
   -p${MYSQL_PASSWORD} \
   ${DATABASE_NAME} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DATABASE_NAME}-${TODAY}.sql.gz

if [ $? -eq 0 ]; then
  echo "Database backup successfully completed"
else
  echo "Error found during backup"
  exit 1
fi


##### Remove backups older than {BACKUP_RETAIN_DAYS} days  #####

DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`

if [ ! -z ${DB_BACKUP_PATH} ]; then
      cd ${DB_BACKUP_PATH}
      if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
            rm -rf ${DBDELDATE}
      fi
fi

在创建或下载脚本之后,请确保将执行权限设置为正确运行。

$ chmod +x /backup/mysql-backup.sh

使用crontab -e命令在系统上编辑crontab。添加以下设置以在凌晨3点启用备份。

0 3 * * * root /backup/mysql-backup.sh