1. 程式人生 > >windows python2下停止,清空,啟動tomcat

windows python2下停止,清空,啟動tomcat

import socket
import os
import os.path
import shutil
import time
# 獲取本機IP地址
def get_host_ip():
    """
    get host ip address
    獲取本機IP地址

    :return:
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()

    return ip

#檢測埠是否被佔用
def is_port_used(ip, port):
    """
    check whether the port is used by other program
    檢測埠是否被佔用

    :param ip:
    :param port:
    :return:
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip, port))
        return True
    except OSError:
        return False
    finally:
        s.close()
# 啟動tomcat
def startTomcat():
   os.chdir(r"E:\\aaaaa\\apache-tomcat\\apache-tomcat-8.0.11\\bin")
   os.system(".\startup.bat")
# 關閉tomcat
def shutdownTomcat():
    os.chdir(r"E:\\aaaaa\\apache-tomcat\\apache-tomcat-8.0.11\\bin")
    os.system(".\shutdown.bat")

CUR_PATH = r'E:\aaaaa\apache-tomcat\apache-tomcat-8.0.11\work\Catalina'
#刪除當前目錄下的全部
def del_file(path):
    shutil.rmtree(CUR_PATH)
path=r'E:\aaaaa\apache-tomcat\apache-tomcat-8.0.11\webapps'
#當前目錄中需要保留的檔案
#filesList=['a.txt','b.txt']
#當前目錄中需要保留的資料夾
dirsList=['docs','examples','host-manager','manager','ROOT']
#獲取檔案字尾名
def suffix( file, *suffixName ) :
    array = map( file.endswith, suffixName )
    if True in array :
        return True
    else :
        return False
def DeleteFiles(path, remainDirsList):
    dirsList = os.listdir(path)
    for f in dirsList:
        if f not in remainDirsList:
            filePath = os.path.join(path,f)
            if os.path.isdir(filePath):
                shutil.rmtree(filePath, True)
        if suffix( f,'.war'):
            os.remove(filePath)
# 測試
if __name__ == '__main__':
    host_ip = get_host_ip()
    print(host_ip)
    flag=is_port_used(host_ip, 8080)
    print(flag)
    if flag:
        print('關閉----》刪除-----》開啟')
        print('開始關閉')
        shutdownTomcat()
        time.sleep(5)
        print('開始刪除')
        del_file(CUR_PATH)
        DeleteFiles(path,dirsList)
        time.sleep(10)
        print('開始重啟')
        startTomcat()
    else:
        print('刪除-----》開啟')
        del_file(CUR_PATH)
        DeleteFiles(path,dirsList)
        print('關閉----》開啟2')
        startTomcat()