import socket import time import os import random path = r'G:apache-tomcat-7.0.92-windows-x64apache-tomcat-7.0.92in' # 服务器tomcat路径 ip = "127.0.0.1" port = 8080 file_path = r'D: omcatlogs' # 记录每次脚本执行的日志文件文件夹路径 def tomcat(otherStyleTime, logfile): os.chdir(path=path) # 切换到Tomcat工作目录 os.system("shutdown.bat") # 首先杀死脚本 os.system("echo %s can't connect to port 8080, stop tomcat >> %s" % (otherStyleTime, logfile)) time.sleep(random.randint(1, 4)) # 随机睡几秒 os.system("startup.bat") # 启动脚本 os.system("echo %s tomcat restart! >> %s" % (otherStyleTime, logfile)) if __name__ == '__main__': while True: try: # 尝试链接Tomcat res = socket.socket(socket.AF_INET, socket.SOCK_STREAM) res.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if res.connect((ip, port)): time.sleep(4) res.shutdown(2) except ConnectionRefusedError as e: print("ConnectionRefusedError") logfile = file_path + '\%s.log' % (time.strftime('%Y%m%d', time.localtime())) # 日志文件存放处 now = int(time.time()) timeArray = time.localtime(now) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) # 获取固定格式时间的字符串 tomcat(otherStyleTime, logfile) except OSError as e: print("OSError") finally: time.sleep(random.randint(3, 5))
# 貌似还有更加简单的写法,写法n多种