VPS 自动备份脚本

没事自己写了两个脚本,一个是备份网站文件,另一个是备份数据库和配置文件,并把备份文件发送到邮箱。

安装 mutt:

yum install mutt

vim ~/.muttrc
# Add the following
set envelope_from=yes
set from=backup@yourdomain.com
set realname="Backup"
set use_from=yes

backup.sh:

#!/bin/bash
# This script run at 02:00 every Tuesday

str_time=$(date +"%Y-%m-%d")
dir_back=/home/backup/
tar_file=${dir_back}backup-$str_time.tar

mail="your@email.com"
text="Backup File $str_time"

declare -a file
file[0]=/usr/local/nginx/html/blog
file[1]=/other-file

####################################

if [ -d $dir_back ]; then
    rm -rf $dir_back
fi

mkdir -p $dir_back

list=${dir_back}file.lst

# files
for var in ${file[@]}; do
    echo $var >> $list
done

tar zcPf $tar_file.gz `cat $list`

split -b 20m -a 3 -d $tar_file.gz ${dir_back}backup-$str_time.part.
#cat ${dir_back}backup-* > ${dir_back}backup.tar.gz

for var in ${dir_back}*.part.*; do
    echo $text | mutt -a $var -s "$text" $mail
    sleep 30s
done

config.sh:

#!/bin/bash
# This script run at 01:00 everyday

str_time=$(date +"%Y-%m-%d")
sql_user=your_mysql_user
sql_pass=your_mysql_pwd
dir_back=/home/backup/
tar_file=${dir_back}config-$str_time.tar

tsk_list=${dir_back}crontab-$str_time

mail="your@email.com"
text="Config File $str_time"

declare -a data
data[0]=mysql_db_1
data[1]=mysql_db_2

declare -a file
file[0]=/etc/init.d/nginx
file[1]=/etc/init.d/php-fpm
file[2]=/etc/nginx/nginx.conf
file[3]=/etc/nginx/fastcgi_php
file[4]=/etc/nginx/vhost
file[5]=/etc/php-fpm.ini
file[6]=/etc/php.ini
file[7]=/etc/my.cnf
file[8]=/other-file

####################################

if [ -d $dir_back ]; then
    rm -rf $dir_back
fi

mkdir -p $dir_back

list=${dir_back}file.lst

# crontab
crontab -l >> $tsk_list
echo $tsk_list >> $list

# mysql
for var in ${data[@]}; do
    sql_file=${dir_back}db-$var-$str_time.sql
    mysqldump -u$sql_user -p$sql_pass $var > $sql_file
    echo $sql_file >> $list
done

# files
for var in ${file[@]}; do
    echo $var >> $list
done

tar zcPf $tar_file.gz `cat $list`

#split -b 20m -a 3 -d $tar_file.gz ${dir_back}backup-$str_time.part.
#cat ${dir_back}backup-* > ${dir_back}backup.tar.gz

for var in ${dir_back}config-*; do
    echo $text | mutt -a $var -s "$text" $mail
    sleep 30s
done

crontab:

0 2 * * 2 /bin/bash /your-script-path/backup.sh
0 1 * * * /bin/bash /your-script-path/config.sh

《VPS 自动备份脚本》有一个想法

发表评论

电子邮件地址不会被公开。 必填项已用*标注