1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #!/usr/bin/env python3 # -*- coding: utf-8 -*-
import os import time import subprocess import psutil from datetime import datetime
def is_process_running(process_keyword): """检查包含指定关键字的进程是否在运行""" try: for proc in psutil.process_iter(['name', 'cmdline']): try: # 检查进程名 if process_keyword.lower() in proc.info['name'].lower(): return True
# 检查命令行 if proc.info['cmdline']: cmdline_str = ' '.join(proc.info['cmdline']).lower() if process_keyword.lower() in cmdline_str: return True except (psutil.NoSuchProcess, psutil.AccessDenied): continue except Exception as e: print(f"[ERROR] 检查进程时出错: {e}") return False
def execute_script(script_path): """执行启动脚本""" if not os.path.exists(script_path): print(f"[ERROR] 脚本不存在: {script_path}") return False
try: result = subprocess.run( script_path, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) print(f"[INFO] 脚本执行成功") if result.stdout: print(f"[OUTPUT] {result.stdout}") return True except subprocess.CalledProcessError as e: print(f"[ERROR] 脚本执行失败 (返回码: {e.returncode})") print(f"[ERROR OUTPUT] {e.stderr}") return False
def main(): # 配置参数(请根据实际情况修改) PROCESS_KEYWORD = "Office" # 要监控的进程关键字 STARTUP_SCRIPT = "cd /opt/Seeyon/G6N/OfficeTrans && ./startup.sh" # 启动脚本路径 CHECK_INTERVAL = 10 # 检查间隔(秒)
print(f"[INFO] 开始监控进程: {PROCESS_KEYWORD}") print(f"[INFO] 启动脚本: {STARTUP_SCRIPT}") print(f"[INFO] 检查间隔: {CHECK_INTERVAL}秒")
try: while True: current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if is_process_running(PROCESS_KEYWORD): print(f"[{current_time}] [INFO] 进程运行正常") else: print(f"[{current_time}] [WARNING] 进程不存在,尝试启动...") #execute_script(STARTUP_SCRIPT)
time.sleep(CHECK_INTERVAL)
except KeyboardInterrupt: print("\n[INFO] 监控脚本被中断") except Exception as e: print(f"[ERROR] 监控过程中发生错误: {e}")
if __name__ == "__main__": main()
|