生产环境备份shell脚本实例代码

发布时间:2020-10-18编辑:脚本学堂
本文介绍了生产环境中备份数据库与网站内容的shell脚本,多个shell备份代码,在线压缩备份文件,测试可用,有需要的朋友参考下。

说明:
以下数据库备份、网站内容备份、备份同步脚本经测试均可用,大家放心使用。

1,批量备份多个数据库
 

复制代码 代码示例:

#!/bin/bash
BACKUP_HOST="localhost"

BACKUP_USER="root"

BACKUP_PASS="123456"

BACKUP_DIR="/backup/mysql"

BACKUP_DBNAME="one two three"

COPIES=10

mysqldump="mysqldump"

TIMEPOINT=$(date +%Y-%m-%d)

MYSQLDUMP_OPTS="-h $BACKUP_HOST -u$BACKUP_USER -p$BACKUP_PASS"

umask 0077

test ! -d "$BACKUP_DIR" && mkdir -p "$BACKUP_DIR"

test ! -w $BACKUP_DIR && echo "Error: $BACKUP_DIR is un-writeable." && exit 0

for dbname in $BACKUP_DBNAME

do

test ! -d "$BACKUP_DIR/$dbname" && mkdir -p "$BACKUP_DIR/$dbname"

$MYSQLDUMP $MYSQLDUMP_OPTS $dbname | gzip > $BACKUP_DIR/$dbname/$dbname.$TIMEPOINT.sql.gz

done

find $BACKUP_DIR -type f -mtime +$COPIES -delete

2,网站目录备份的shell/ target=_blank class=infotextkey>shell脚本
 

复制代码 代码示例:

#!/bin/bash

BACKUP_DIR=/backup/website

WEBSITE_DIR=/www

TIMEPOINT=$(date +%Y-%m-%d)

COPIES=10

test ! -d "$BACKUP_DIR" && mkdir -p "$BACKUP_DIR"

test ! -w $BACKUP_DIR && echo "Error: $BACKUP_DIR is un-writeable." && exit 0

umask 0077

tar -zcf $BACKUP_DIR/www.$TIMEPOINT.tar.gz $WEBSITE_DIR

find $BACKUP_DIR -type f -mtime +$COPIES -delete

3,目录rsync同步(需先安装配置rsync)
rsync安装方法:
linux rsync同步备份的安装与配置
Linux下架设rsync服务器的案例分享
linux下rsync服务配置一例
有关rsync安装与配置的实例教程
inotify+rsync配置实例详解
rsync+inotify 文件同步配置实例
有关rsync服务器端配置及客户端的使用
rsync文件同步配置一例
linux rsync同步设置指南

代码:
 

复制代码 代码示例:

#!/bin/sh
srcdir1=/www/example1.com
srcdir2=/www/example2.com
dstdir3=jszb@111.111.111.111::example1
dstdir4=jszb@222.222.222.222::example2

rsync -avz --delete --progress --password-file=/backup/bash/rsync.pas $srcdir1 $dstdir3 &

rsync -avz --delete --progress --password-file=/backup/bash/rsync.pas $srcdir2 $dstdir4 &

4,nginx日志切割
 

复制代码 代码示例:
#!/bin/bash
logs_path="/usr/local/webserver/nginx/logs/"
mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path}access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_$(date -d "yesterday" +"%Y%m%d").log
kill -USR1 `cat /usr/local/webserver/nginx/nginx.pid`