shell脚本部分:
#!/bin/bash 主脚本 (./cem-demo_publish_front) (./cem-demo_publish_backend) #!/bin/bash 后端脚本 cd /data/www/cem-base-demo && git pull && ./restart_all.sh #!/bin/bash 前端脚本 cd /data/www/cem-front-demo && rm -fr dist && git pull && npm run build #cp /data/www/cem-front/index.html /data/www/cem-base/static/index_prod.html cp -fr /data/www/cem-front-demo/dist /data/www/cem-base-demo/ #!/bin/bash restart_all.sh python restart_port.py all 9060 4
Python restart_port.py 文件
1 # encoding=utf8 2 3 import sys 4 import commands 5 import os 6 import re 7 import getpass 8 import time 9 import requests 10 11 current_user = getpass.getuser() 12 13 14 def get_pid(port): 15 output = commands.getoutput(‘ps aux|grep "[p]ython main.py"‘) 16 lines = output.split(‘\n‘) 17 ps_dict = {} 18 re_obj = re.compile(r‘%s +(\d+).*main\.py (\d+)$‘ % current_user) 19 for line in lines: 20 result = re_obj.findall(line) 21 if not result: 22 continue 23 pid, port1 = result[0] 24 ps_dict[port1] = pid 25 26 return ps_dict.get(str(port)) 27 28 29 def usage(): 30 print ‘Usage: restart_port.py <port|all> <port_from> <process_number>‘ 31 sys.exit(1) 32 33 34 def kill_port(port): 35 pid = get_pid(port) 36 if pid: 37 cmd = ‘kill -9 %s‘ % pid 38 print ‘killing process ...‘ 39 status, output = commands.getstatusoutput(cmd) 40 # time.sleep(2) 41 print ‘process %s for port %s is killed‘ % (pid, port) 42 43 44 def restart_port(port): 45 pid = get_pid(port) 46 if pid: 47 cmd = ‘kill -9 %s‘ % pid 48 status, output = commands.getstatusoutput(cmd) 49 time.sleep(1) 50 cmd = ‘nohup python main.py %s >> logs/p_%s.log &‘ % ( 51 port, port) 52 # status,output = commands.getstatusoutput(cmd) 53 os.system(cmd) 54 55 56 def check_port_is_health(port): 57 need_check = True 58 while need_check: 59 time.sleep(1) 60 try: 61 response = requests.get(‘http://127.0.0.1:%s‘ % port) 62 if response.status_code == 200: 63 need_check = False 64 else: 65 need_check = True 66 print ‘response.status_code=‘, response.status_code 67 except Exception, e: 68 print ‘port=‘, port, str(e) 69 need_check = True 70 if need_check: 71 print ‘port=‘, port 72 restart_port(port) 73 74 if __name__ == ‘__main__‘: 75 try: 76 port = sys.argv[1] 77 except: 78 usage() 79 80 if port == ‘all‘: 81 try: 82 port_from = int(sys.argv[2]) 83 except: 84 usage() 85 86 try: 87 process_number = int(sys.argv[3]) 88 except: 89 usage() 90 91 for port in range(port_from, port_from + process_number): 92 restart_port(port) 93 # check_port_is_health(port) 94 elif port == ‘kill‘: 95 try: 96 port_from = int(sys.argv[2]) 97 except: 98 usage() 99 100 try: 101 process_number = int(sys.argv[3]) 102 except: 103 usage() 104 105 for port in range(port_from, port_from + process_number): 106 kill_port(port) 107 else: 108 restart_port(port) 109 check_port_is_health(port)
restart_port.py
时间: 2024-10-10 08:07:54