zoukankan      html  css  js  c++  java
  • tomcat 部署脚本

    将一下3个脚本放到一个目录里,做成一个 python 的包即可使用


    脚本介绍

    操作服务脚本

    #!/usr/bin/env python
    # _*_coding:utf-8_*_
    # Author: "Edward.Liu"
    # Author-Email: lonnyliu@126.compile
    
    """
        process hanlde files incloud
            1.process status
                use request get Url returncode
            2.process Stop
                use psutil kill process
            3.process start
                use subprocess run shell start process
            4.process log
                use process logs
            5.process restart
    """
    
    # Improt Libary
    import psutil
    from subprocess import PIPE, Popen, STDOUT
    import os
    import sys
    import requests
    import datetime
    
    # Set vars
    process_name = "/software/apache-tomcat-jenkins"
    url = "http://172.31.1.230:8080"
    
    
    def process_id():
        # use process name get process pid
        process_base_str = "-Dcatalina.base=%s" % process_name
        pid = {}
        for proc in psutil.process_iter():
            try:
                pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline'])
            except psutil.NoSuchProcess:
                pass
            else:
                if process_base_str in pinfo.get('cmdline'):
                    pid[process_name] = pinfo.get('pid')
        return pid
    
    
    def process_judgment():
        # 判断 URL 的状态码
        messages = ""
        try:
            jenkins_r = requests.get(url, timeout=None)
            return jenkins_r.status_code
        except requests.ConnectTimeout:
            messges = "Timeout"
            return messges
        except requests.ConnectionError:
            messages = "connection"
            return messages
        except requests.HTTPError:
            messages = "httperror"
            return messages
        else:
            return messages
    
    
    def process_status():
        # judgment process status
        if not process_id().get(process_name) is None:
            if process_judgment() == 200:
                print "33[32mProcess %s normal33[0m" 
                    % process_name.split('/')[2]
            else:
                print "33[31mProcess Dont Access By:%s33[0m" % url + "
    "
                    "33[31mMesages:%s" % process_judgment()
        else:
            print "33[31mProcess %s does not exist" % process_name.split('/')[2]
    
    
    def process_log_info():
        process_log = "tail -f %s/logs/catalina.out " % process_name
        process_logs = Popen(process_log, shell=True,
                             stdout=PIPE, stderr=STDOUT)
        returncode = process_logs.poll()
        try:
            while returncode is None:
                line = process_logs.stdout.readline()
                returncode = process_logs.poll()
                line = line.strip()
                print line
            print returncode
        except KeyboardInterrupt:
            print 'ctrl+d or z'
    
    
    def process_kill():
        # judgment process exist
        if process_id().get(process_name) is None:
            print "33[31mProcess %s is Not Started" % process_name.split('/')[2]
            sys.exit(0)
        elif not process_id().get(process_name) is None 
                and process_judgment() != 200:
            print "33[31mProcess %s is Started But Process access Failed 
                Messages:" % (process_name, process_judgment())
            sys.exit(0)
        # stop process
        PROCESSID = process_id().get(process_name)
        p = psutil.Process(pid=PROCESSID)
        p.kill()
        if process_id().get(process_name) is None:
            print "33[32mprocess %s stop OK!!!33[0m" 
                % process_name.split('/')[2]
        else:
            print "33[31mProcess %s Stop Failed!!![033[0m" 
                % process_name.split('/')[2]
    
    
    def process_init():
        # start process
        os.environ["JAVA_HOME"] = "/software/java_1.7"
        start_time = datetime.datetime.now()
        process_init_command = "%s/bin/startup.sh" % process_name
        start = Popen(process_init_command, stdout=PIPE,
                      stderr=PIPE, shell=True)
        stdout, stderr = start.communicate()
        print stderr
        print "33[32mWaitting Process %s Start OK !!!33[0m" 
            % process_name.split('/')[2]
        while process_judgment() != 200:
            pass
        end_time = datetime.datetime.now()
        print "33[32mprocess start time(s):%s33[0m" 
            % (end_time - start_time).seconds
    View Code

    操作文件脚本

     1 #!/usr/bin/env python
     2 # _*_coding:utf-8_*_
     3 # Author: "Edward.Liu"
     4 # Author-Email: lonnyliu@126.compile
     5 
     6 
     7 import os
     8 import zipfile
     9 import datetime
    10 
    11 # set process directory vars
    12 DEPLOY_ENV = "mobile"
    13 DEPLOY_WAR = "cybershop-%s-0.0.1-SNAPSHOT.war" % DEPLOY_ENV
    14 UPLOAD_WAR_DIRECTORY = "/software/source_files"
    15 DEPLOY_TMP = "/software/deploy_tmp/"
    16 DEPLOY_REALY = "/software/deploy_%s/" % DEPLOY_ENV
    17 STATIC_DIRECTORY = "/data/www"
    18 PICTURE_DIRECTORY = "/software/picture"
    19 # Set process Diectory Vars end
    20 # Set Process Used dir
    21 Source_Path = "%s/%s" % (UPLOAD_WAR_DIRECTORY, DEPLOY_WAR)
    22 now_time = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M")
    23 Last_File = "%s%s-%s" % (DEPLOY_TMP, DEPLOY_WAR.split('.war')[0], now_time)
    24 # Set process Used End
    25 
    26 
    27 def process_judgment_dir():
    28     # 判断目录是否存在
    29     if not os.path.exists(UPLOAD_WAR_DIRECTORY):
    30         os.makedirs(UPLOAD_WAR_DIRECTORY)
    31     elif not os.path.exists(DEPLOY_TMP):
    32         os.makedirs(DEPLOY_TMP)
    33     elif not os.path.exists(DEPLOY_REALY):
    34         os.makedirs(DEPLOY_REALY)
    35     else:
    36         print "33[32mUsed Dir Is exists33[0m"
    37 
    38 
    39 def process_source():
    40     """
    41         1.解压部署文件
    42         2.创建图片存放目录
    43     """
    44     ret = 0
    45     # 图片目录创建
    46     Last_File_Pic = "%s/assets" % Last_File
    47     if not os.path.exists(Last_File):
    48         # 创建程序目录
    49         os.makedirs(Last_File)
    50         # 创建图片目录
    51         os.makedirs(Last_File_Pic)
    52         try:
    53             zip_ref = zipfile.ZipFile(Source_Path, 'r')
    54             zip_ref.extractall(Last_File)
    55             zip_ref.close()
    56             ret = 1
    57             return ret
    58         except IOError:
    59             print "33[31m%s Is Not Exists Please send Files33[0m" 
    60                 % DEPLOY_WAR.split('.war')[0]
    61         return ret
    62 
    63 
    64 def process_link():
    65     if process_source() == 1:
    66         # 创建项目启动所需链接
    67         dest_pic = "%s/assets/upload" % Last_File
    68         dest_static = "%s/www" % Last_File
    69         os.symlink(PICTURE_DIRECTORY, dest_pic)
    70         os.symlink(STATIC_DIRECTORY, dest_static)
    71         # 创建项目启动所需链接----END
    72         # 创建启动程序链接
    73         dest_deploy_path = "%s%s" % (DEPLOY_REALY, DEPLOY_WAR.split('.war')[0])
    74         os.symlink(Last_File, dest_deploy_path)
    75         if os.path.islink(dest_deploy_path):
    76             print "33[32mCrate Link Process Is Scueeful33[0m"
    77         # 创建启动程序链接----END
    View Code

    整合脚本

    #!/usr/bin/env python
    # _*_coding:utf-8_*_
    # Author: "Edward.Liu"
    # Author-Email: lonnyliu@126.compile
    
    import handle_files
    import handle_process
    import argparse
    import sys
    import time
    import datetime
    
    
    def check_arg(args=None):
        parser = argparse.ArgumentParser(
            description="EG: '%(prog)s'  -p start|stop")
        parser.add_argument('-p', '--process', default='log',
                            help='Input One of the {start|stop|status|log}')
        parser.add_argument('-v', '--version', action='version',
                            version='%(prog)s 1.1')
        if len(sys.argv) == 1:
            parser.print_help()
            sys.exit(1)
        return parser.parse_args(args)
    
    
    def main():
        args = check_arg(sys.argv[1:])
        if args.process == "start":
            handle_process.process_init()
        elif args.process == "stop":
            handle_process.process_kill()
        elif args.process == "status":
            handle_process.process_status()
        elif args.process == "log":
            handle_process.process_log_info()
        elif args.process == "restart":
            handle_process.process_kill()
            time.sleep(10)
            handle_process.process_init()
        elif args.process == "deploy":
            handle_files.process_judgment_dir()
            print "33[32mWaitting Unzip project33[0m" + "." * 10
            start_time = datetime.datetime.now()
            handle_files.process_source()
            end_time = datetime.datetime.now()
            print "33[32mPorject Unzip End-time(s):%s33[0m" 
                  % (end_time - start_time).seconds
            handle_process.process_kill()
            handle_files.process_link()
            handle_process.process_init()
    
    
    if __name__ == '__main__':
        main()
    View Code
  • 相关阅读:
    计算函数执行时间
    Go语言生成随机数
    413 Request Entity Too Large
    JavaScript变量与数据类型详解
    OAuth2.0认证详解
    prompt的工作原理
    JS 实现上传图片
    移动端的长按事件的实现
    实现自动关闭当前页面的效果
    前端异常捕获与上报
  • 原文地址:https://www.cnblogs.com/edwardlogs/p/Tomcat-Process-Deploy.html
Copyright © 2011-2022 走看看