使用Python部署MongoDB

使用Python部署MongoDB

1.思路

在程序中,我们首先在main函数中定义了几个变量,包括当前目录的路径、MongoDB二进制文件所在的路径、MongoDB数据目录所在的路径,以及MongoDB的日志文件。

随后,我们判断MongoDB的安装包是否存在,如果不存在,则通过抛出SystemExit异常的方式结束程序。

在unpackage_mongo函数中,我们通过Python程序得到MongoDB安装包解压以后的目录。如果目录已经存在,则删除该目录。随后,我们使用tarfile解压MongoDB数据库,解压完成后,将命令重命名为mongo目录。

在create_datadir目录中,我们首先判断MongoDB数据库目录是否存在,如果存在,则删除该目录,随后再创建MongoDB数据库目录。

在start_mongod函数中,我们执行MongoDB数据库的启动命令启动MongoDB数据库。为了在Python代码中执行shell命令,我们使用了subprocess库。我们将subprocess库执行shell命令的逻辑封装成execute_cmd函数,在执行shell命令时,直接调用该函数即可。

本实验MongoDB版本为:mongodb-Linux-x86_64-rhel70-4.2.3

下载网址:https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.2.3.tgz

2.使用Python部署MongoDB

#!/usr/bin/env python3
# coding:utf-8
# ProjectName: Linux系统管理
# Author:xsh
# CreateTime:2020/6/23 9:00
# FileName:deploy_MongoDB
# Description:使用Python部署MongoDB

#!/usr/bin/python
# coding = utf-8

from __future__ import print_function
import subprocess
import os
import shutil
import tarfile


def execute_cmd(cmd):
    ''' 执行shell命令 '''
    p = subprocess.Popen(cmd, shell=True,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        return p.returncode, stderr
    return p.returncode, stdout


def unpackage_mongo(package, package_dir):
    unpackage_dir = os.path.splitext(package)[0]
    if os.path.exists(unpackage_dir):
        shutil.rmtree(unpackage_dir)
    if os.path.exists(package_dir):
        shutil.rmtree(package_dir)
    # 解压
    t = tarfile.open(package, 'r:gz')
    t.extractall('.')
    # 重命名mongodb-Linux-x86_64-rhel70-4.2.3为mongo
    shutil.move(unpackage_dir, 'mongo')


def create_datadir(data_dir):
    if os.path.exists(data_dir):
        shutil.rmtree(data_dir)
    os.mkdir(data_dir)


def format_mongod_commamd(package_dir, data_dir, logfile):
    mongod = os.path.join(package_dir, 'bin', 'mongod')
    mongod_format = """{0} --fork --dbpath {1} --logpath {2}"""
    return mongod_format.format(mongod, data_dir, logfile)


def start_mongod(cmd):
    returncode, out = execute_cmd(cmd)
    if returncode != 0:
        raise SystemExit('execute {0} error:{1}'.format(cmd, out))
    else:
        print('execute {0} successfuly.'.format(cmd))


def main():
    package = 'mongodb-linux-x86_64-rhel70-4.2.3.tgz'
    cur_dir = os.path.abspath('.')
    package_dir = os.path.join(cur_dir, 'mongo')
    data_dir = os.path.join(cur_dir, 'mongodata')
    logfile = os.path.join(data_dir, 'mongod.log')

    if not os.path.exists(package):
        raise SystemExit('{0} not found.'.format(package))

    unpackage_mongo(package, package_dir)
    create_datadir(data_dir)
    start_mongod(format_mongod_commamd(package_dir, data_dir, logfile))


if __name__ == '__main__':
    main()

3.运行结果

Last login: Tue Jun 23 18:36:57 2020 from 192.168.1.3
[root@Python ~]# cd /opt
[root@Python opt]# ls
ab.txt              deploy_MongoDB.py  find_files.py                          os模块          test_dir.py
a.jpg               e.jpg              install_python.py                      rh              walk_dir.py
common_commands.py  example            mongodb-linux-x86_64-rhel70-4.2.3.tgz  shutil_file.py
[root@Python opt]# python3 deploy_MongoDB.py 
execute /opt/mongo/bin/mongod --fork --dbpath /opt/mongodata --logpath /opt/mongodata/mongod.log successfuly.
[root@Python opt]# ln -s /opt/mongo/bin/mongod /usr/bin/mongod
[root@Python opt]# mongod --dbpath /opt/mongodata
2020-06-23T18:40:19.548+0800 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten] MongoDB starting : pid=7971 port=27017 dbpath=/opt/mongodata 64-bit host=Python
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten] db version v4.2.3
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten] git version: 6874650b362138df74be53d366bbefc321ea32d4
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten] allocator: tcmalloc
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten] modules: none
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten] build environment:
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten]     distmod: rhel70
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten]     distarch: x86_64
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten]     target_arch: x86_64
2020-06-23T18:40:19.562+0800 I  CONTROL  [initandlisten] options: { storage: { dbPath: "/opt/mongodata" } }
2020-06-23T18:40:19.562+0800 E  STORAGE  [initandlisten] Failed to set up listener: SocketException: Address already in use
2020-06-23T18:40:19.563+0800 I  CONTROL  [initandlisten] now exiting
2020-06-23T18:40:19.563+0800 I  CONTROL  [initandlisten] shutting down with code:48
[root@Python opt]# netstat -anput | grep mongo
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      7817/mongod         
[root@Python opt]# 

使用Python部署MongoDB_第1张图片

4.bin目录下的几个文件说明

[root@Python opt]# ls
ab.txt              e.jpg              mongo                                  rh
a.jpg               example            mongodata                              shutil_file.py
common_commands.py  find_files.py      mongodb-linux-x86_64-rhel70-4.2.3.tgz  test_dir.py
deploy_MongoDB.py   install_python.py  os模块                                 walk_dir.py
[root@Python opt]# cd mongo
[root@Python mongo]# ls
bin  LICENSE-Community.txt  MPL-2  README  THIRD-PARTY-NOTICES  THIRD-PARTY-NOTICES.gotools
[root@Python mongo]# cd bin
[root@Python bin]# ls
bsondump         mongo   mongodump    mongofiles   mongoreplay   mongos     mongotop
install_compass  mongod  mongoexport  mongoimport  mongorestore  mongostat

bin目录下的几个文件说明:

文件 作用
mongo 客户端程序,连接MongoDB
mongod 服务端程序,启动MongoDB
mongodump 备份程序
mongoexport 数据导出程序
mongofiles GridFS工具,内建的分布式文件系统
mongoimport 数据导入程序
mongorestore 数据恢复程序
mongos 数据分片程序,支持数据的横向扩展
mongostat 监视程序

这只是我的一些浅薄的见解,望多指教!

你可能感兴趣的:(python)