版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29347295/article/details/83618178
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()