cat init_MongoDB.sh
#!/bin/bash
export lang=C
export my_port=27019
export my_dbpath=/opt/var/data/mongodb #数据存放目录
export my_logpath=/opt/var/logs/mongodb #日志存放目录
export my_keyFile=mongodb.key #集群中节点通信要用到keyfile
export my_pidfilepath=master.pid #进程文件,方便停止mongodb
export my_directoryperdb=true #为每一个数据库按照数据库名建立独立目录存放
export my_logappend=true #以追加的方式记录日志
export my_replSet=RS1 #replica set的名字
export my_bind_ip=0.0.0.0 #mongodb所绑定的ip地址
export my_port=27019 #mongodb进程所使用的端口号,默认为27017
export my_oplogSize=1000 #mongodb操作日志文件的最大大小。单位为Mb,默认为硬盘剩余空间的5%
export my_fork=true #是否后台方式运行进程
export my_maxConns=20000 #最大连接数
echo '#1.关闭本地的MongoDB'
ps -ef |grep mongodb
#service mongodb stop
echo '#2.清空本地MongoDB的安装文件'
rm -rf /opt/server/*
rm -rf /opt/var/data/*
#rm -rf /opt/var/log/
echo '#3.创建MongoDB的介质存放目录、安装目录'
mkdir -p /opt/soft/
mkdir -p /opt/server/
mkdir -p /opt/var/data/mongodb/
mkdir -p /opt/var/logs/mongodb/
echo '#4.拷贝安装介质'
mv /softwares/mongodb-linux-x86_64-rhel62-4.0.0.tgz /opt/soft/
cd /opt/soft/
ls
echo '#5.解包该介质'
tar zxvf mongodb-linux-x86_64-rhel62-4.0.0.tgz
echo '#6.把解包文件移动至安装目录'
mv mongodb-linux-x86_64-rhel62-4.0.0 /opt/server/mongodb
echo '#7.修改并刷新本地的profile文件'
cat <<EOF >/etc/profile
export PATH=$PATH:/opt/server/mongodb/bin
EOF
source /etc/profile
echo '#8.生成本地的key file文件,授权600'
openssl rand -base64 100 > /opt/var/data/mongodb/mongodb.key
chmod 600 /opt/var/data/mongodb/mongodb.key
echo '#9.修改MongoDB的初始化参数文件'
dd if=/dev/zero of=/opt/server/mongodb/mongodb.conf count=0
cat <<EOF > /opt/server/mongodb/mongodb.conf
dbpath=$my_dbpath
logpath=$my_logpath/alert_mongodb.log
pidfilepath=$my_dbpath/$my_pidfilepath
keyFile=$my_dbpath/$my_keyFile
directoryperdb=$my_directoryperdb
logappend=$my_logappend
#replSet=RS1
bind_ip=$my_bind_ip
port=$my_port
#auth=true
oplogSize=$my_oplogSize
fork=$my_fork
noprealloc=$my_noprealloc
maxConns=$my_maxConns
EOF
echo '#10.修改MongoDB的启动脚本,并授于 执行的权限'
cat <<EOF > /etc/rc.d/init.d/mongodb
#!/bin/sh
# chkconfig: - 64 36
# description:mongod
case $1 in
start)
/opt/server/mongodb/bin/mongod -f /opt/server/mongodb/mongodb.conf
;;
stop)
/opt/server/mongodb/bin/mongo 127.0.0.1:$my_port/admin --eval "db.shutdownServer()"
;;
status)
/opt/server/mongodb/bin/mongo 127.0.0.1:$my_port/admin --eval "db.stats()"
;;
esac
EOF
chmod +x /etc/rc.d/init.d/mongodb
echo '#11.启动MongoDB'
service mongodb start
#about to fork child process, waiting until server is ready for connections.
#forked process: 2556
#child process started successfully, parent exiting
mongo 127.0.0.1:$my_port <<EOF
use admin;
db.createUser(
{ user: "root",
pwd: "root",
roles: [ { role: "root", db: "admin" } ]
}
);
db.auth("root","root");
show dbs;
show users;
EOF
ps -ef |grep mongodb
#db.shutdownServer();