1.1 mongodb的部署情况
#### 软件部署的位置
/data/mongodb/apps/mongodb
# 是个软链接文件,指向/data/mongodb/apps/mongodb-linux-x86_64-rhel70-4.0.2
#### mongodb实例部署情况(是用操作系统下app用户来启动的)
[root@vm7-200 ~]# tree -Lp 1 /data/mongodb/27017/
/data/mongodb/27017/
├── [drwxr-xr-x] conf
├── [drwxr-xr-x] data
├── [drwxr-xr-x] logs
├── [drwxr-xr-x] run
└── [drwxr-xr-x] scripts
5 directories, 0 files
#### mongodb实例开启了认证的
用户:root
密码:root123456
角色:root
认证库:admin
1.2 备份脚本
创建相关的目录
mkdir -p /data/bakmongodb/{data,script}
# /data/bakmongodb/data目录下存放备份数据(每天一个目录)
# /data/bakmongodb/script目录下存放以下的脚本
脚本内容
脚本只能root用户来执行(脚本中进行了限制);
这样我的脚本就会放在root用户下(定时任务)
#!/bin/bash
#
# explain: mongodump tool backup MongoDB(mongod)
# author:chenliang tel:18382024220
#
#### Define variables
RETVAL=0
CommPath="/data/mongodb/apps/mongodb/bin"
Host="127.0.0.1"
Port="27017"
User="root"
Password="root123456"
AuthenDb="admin"
Time1=$(date +%F-%H:%M)
SaveDir1="/data/bakmongodb/data"
SaveDir2="$SaveDir1/$Time1"
BusinesLibrary=( $(echo "show dbs;" | $CommPath/mongo --host=$Host --port=$Port --username=$User --password=$Password \
--authenticationDatabase=$AuthenDb --shell |sed '1,4'd|sed '$'d|cut -d " " -f1|grep -Ev "admin|config|local" )
)
#### Determine the user to execute
if [ $UID -ne $RETVAL ];then
echo "Must be root to run scripts"
exit 1
fi
#### Determine $SaveDir1 dir is exists.
#### if it does exists,create a directory.
#### Failed to create directory,exit script.
if [ ! -d $SaveDir1 ];then
mkdir -p $SaveDir1
RETVAL=$?
if [ $RETVAL -eq 0 ];then
echo "Create \"$SaveDir1\" directory successful"
else
echo "Create \"$SaveDir1\" directory failure"
exit 1
fi
fi
#### Determine $SaveDir2 dir is exists.
#### if it does exists,create a directory.
#### Failed to create directory,exit script.
if [ ! -d $SaveDir2 ];then
mkdir -p $SaveDir2
RETVAL=$?
if [ $RETVAL -eq 0 ];then
echo "Create \"$SaveDir2\" directory successful"
else
echo "Create \"$SaveDir2\" directory failure"
exit 1
fi
fi
### For loop depots backup
for((i=0;i<${#BusinesLibrary[*]};i++))
do
$CommPath/mongodump --host=$Host --port=$Port --username=$User --password=$Password --authenticationDatabase=$AuthenDb \
-d ${BusinesLibrary[i]} -o $SaveDir2 --gzip
done
### Delete data in the last 2 days
find $SaveDir1 -maxdepth 1 -type d -mtime +2 |xargs rm -fr