进程服务监测与自愈

#!/usr/bin/python3
# encoding: utf-8
#filename: service-detection-repair.py
#author: gaohaixiang
#writetime:202403041043

"""
# 定时任务监测示例
*/5 * * * * python3 /data/processlog/service-detection-repair.py systemctlCheck nginx
*/5 * * * * python3 /data/processlog/service-detection-repair.py processCheck /data/nginx/sbin/nginx /data/nginx/sbin/nginx

# 脚本使用示例:
# systemctl is-active nginx ,检测不是 active 以后就 systemctl restart nginx
python3 service-detection-repair.py systemctlCheck nginx

# pgrep -f /data/nginx/sbin/nginx,该路径为nginx启动的绝对路径,用于检测这个nginx是否存活,
# 若是不存在该nginx,则使用 /data/nginx/sbin/nginx 启动 nginx
# 第一个路径为检测nginx是否存活,第二个路径是绝对路径启动nginx
python3 service-detection-repair.py processCheck /data/nginx/sbin/nginx /data/nginx/sbin/nginx
"""

import time
import subprocess
import sys
import os

# 日期时间获取
def timestamp_time():
    timestamp = int(time.time())
    # 转换成localtime(格式和时间戳一样)
    timelocal = time.localtime(timestamp)
    # 转换成新的时间格式(3016-05-05 20:28:54)
    datetime = time.strftime("%Y%m%d%H%M%S", timelocal)
    return datetime

# 日志文件写入换行间隔
def fileWriteLine(getdatetime,filewrite):
    filewrite.writelines("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n")
    filewrite.writelines(getdatetime+"\n")

# systemctl 进行服务检测
def systemctlCheckService(getdatetime, filewrite,checkCommand):
    fileWriteLine(getdatetime, filewrite)
    filewrite.writelines("systemctlCheckService\n")
    filewrite.writelines(checkCommand+"\n")
    try:
        # 执行检查命令
        status = subprocess.check_output(checkCommand, shell=True).decode('utf-8').strip()
        filewrite.writelines("------服务正常------\n")
        return status == 'active'
    except subprocess.CalledProcessError as e:
        print(f"错误,服务检测的状态是: {e}")
        filewrite.writelines("------服务关闭------\n")
        return False

# systemctl 进行服务重启
def systemctlRestartService(getdatetime, filewrite,restartCommand,serviceName):
    fileWriteLine(getdatetime, filewrite)
    filewrite.writelines("systemctlRestartService\n")
    filewrite.writelines(restartCommand+"\n")
    try:
        # 执行重启命令
        subprocess.check_call(restartCommand, shell=True)
        filewrite.writelines("------服务已经被重启------\n")
        print(f"服务 {serviceName} 已经被重启.")
    except subprocess.CalledProcessError as e:
        filewrite.writelines("------服务重启错误------\n")
        print(f"服务重启错误: {e}")

# systemct 服务进行监测及重启
def systemctlCheck(getdatetime, filewrite,serviceName):
    fileWriteLine(getdatetime, filewrite)
    filewrite.writelines("systemctlCheck\n")
    filewrite.writelines(serviceName+"\n")
    # 检查服务状态的命令
    checkCommand = f'systemctl is-active {serviceName}'
    # 重启服务的命令
    restartCommand = f'sudo systemctl restart {serviceName}'

    # 检查服务是否运行
    if not systemctlCheckService(getdatetime, filewrite,checkCommand):
        filewrite.writelines("------服务停止. 准备进行重启.------\n")
        print(f"服务 {serviceName} 停止. 准备进行重启.")
        systemctlRestartService(getdatetime, filewrite,restartCommand,serviceName)
    else:
        filewrite.writelines("------服务正在运行中.------\n")
        print(f"服务 {serviceName} 正在运行中.")

def processIsRunning(getdatetime, filewrite,servicePath):
    fileWriteLine(getdatetime, filewrite)
    filewrite.writelines("processIsRunning\n")
    filewrite.writelines(servicePath+"\n")
    try:
        # 获取当前脚本的进程ID
        current_pid = str(os.getpid())

        # 使用pgrep检查进程是否存在,并获取所有匹配的PID
        pids = subprocess.check_output(['pgrep', '-f', servicePath, '-d', '\n']).decode('utf-8').strip().split('\n')

        # 移除当前脚本的PID
        pids = [pid for pid in pids if pid != current_pid]

        # 如果移除后仍有其他PID存在,则服务正在运行
        if pids:
            filewrite.writelines("------服务正在运行.------\n")
            print("serviceName 正在运行")
            return True
        else:
            filewrite.writelines("------服务已经停止.------\n")
            print("serviceName 已经停止")
            return False
    except subprocess.CalledProcessError:
        # pgrep在没有找到进程时返回非零退出状态
        print("serviceName 已经停止")
        filewrite.writelines("------服务已经停止.------\n")
        return False

def processStartService(getdatetime,filewrite,startCommand):
    fileWriteLine(getdatetime, filewrite)
    filewrite.writelines("processStartService\n")
    filewrite.writelines(startCommand+"\n")
    try:
        # 执行启动命令
        subprocess.check_output(startCommand, shell=True)
        filewrite.writelines("------已经开始使用这个命令进行启动.------\n")
        print(f"已经开始使用这个命令进行启动: {startCommand}")
    except subprocess.CalledProcessError as e:
        filewrite.writelines("------使用命令进行启动发生错误.------\n")
        print(f"错误,使用这个命令进行启动发生错误 {startCommand}: {e}")

def processCheck(getdatetime, filewrite,serviceMaster):
    fileWriteLine(getdatetime, filewrite)
    filewrite.writelines("processCheck\n")
    #filewrite.writelines(startCommand+"\n")
    for serviceName, serviceInfo in serviceMaster.items():
        servicePath = serviceInfo['servicePath']
        startCommand = serviceInfo['startCommand']

        # 检查服务是否运行
        if not processIsRunning(getdatetime, filewrite,servicePath):
            filewrite.writelines("------服务已关闭。正在尝试启动.------\n")
            print(f"{serviceName} 已关闭。正在尝试启动。")
            processStartService(getdatetime, filewrite,startCommand)
        else:
            filewrite.writelines("------服务正在运行.------\n")
            print(f"{serviceName} 正在运行。")

def main(getdatetime,filewrite):
    fileWriteLine(getdatetime, filewrite)
    filewrite.writelines("main\n")
    # filewrite.writelines(startCommand+"\n")
    if len(sys.argv) > 1:
        if sys.argv[1] == "systemctlCheck" and len(sys.argv) == 3:
            systemctlCheck(getdatetime,filewrite,sys.argv[2])
        elif sys.argv[1] == "processCheck" and len(sys.argv) == 4:
            serviceMaster = {
                'serviceMaster': {
                    'servicePath': sys.argv[2],
                    'startCommand': sys.argv[3]
                },
            }
            processCheck(getdatetime,filewrite,serviceMaster)
        else:
            filewrite.writelines("------脚本携带参数有误.------\n")
            print("脚本携带参数有误")
    else:
        filewrite.writelines("------脚本没有携带参数,请携带正确的参数再运行脚本.------\n")
        print("脚本没有携带参数,请携带正确的参数再运行脚本")


if __name__ == '__main__':
    # 脚本及日志存放路径
    logdir = "/data/processlog/"
    # 日志文件
    processChecklog = "processChecklog.log"
    processfile = logdir + processChecklog

    # 时间获取
    getdatetime = timestamp_time()

    filewrite = open(processfile, "a+", encoding="UTF8")
    # 主函数入口
    main(getdatetime, filewrite)
    filewrite.close()


  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要实现Linux上的进程自动关闭和自动重启,可以编写一个监测进程的脚本。 脚本的思路如下: 1. 首先,需要在Linux上安装inotify-tools软件包来监测文件或目录的状态变化。 2. 在脚本中使用inotifywait命令监测进程的状态文件或进程的关键日志文件。 3. 当进程关闭时,脚本会检测到相关文件发生了变化,并执行相应的操作,比如重启进程。 4. 可以使用while循环来不断监测文件状态的变化,实现持续的监测和重启功能。 伪代码如下所示: ```shell # 设定监测的文件路径 file_to_monitor="/path/to/your/file" # 循环监测文件状态的变化 while true do # 使用inotifywait命令监测文件的状态变化 inotifywait -e modify $file_to_monitor # 文件状态变化时执行的操作 # 检测进程是否关闭,如果关闭就重启进程的命令 # restart_your_process_command done ``` 这个脚本可以根据具体的需求进行修改和扩展,比如添加邮件或者日志通知功能,或者对重启次数进行限制等。可以根据实际情况来优化脚本的策略和逻辑。 ### 回答2: 为了实现Linux进程的自动关闭和自动重启功能,可以编写一个脚本来监测指定进程的状态,并根据需要进行相应的操作。 首先,通过使用ps命令来获取当前进程的状态信息,可以使用以下命令获取指定进程的PID(进程ID): ``` pid=$(ps -ef | grep -v grep | grep "进程名" | awk '{print $2}') ``` 其中,将"进程名"替换为要监测进程的名称。此命令使用grep筛选出与进程名匹配的行,再使用awk提取出PID。 接下来,可以使用kill命令来关闭指定进程,命令如下: ``` kill -9 $pid ``` 其中,$pid是上一步获取的进程的PID。-9参数表示强制终止进程。 为了实现自动重启功能,可以使用nohup命令来重新启动进程,命令如下: ``` nohup 进程名 & ``` 此命令使用nohup命令将进程以守护进程的方式运行,并且将输出重定向到nohup.out文件中。&符号表示在后台运行。 最后,将以上的命令封装成一个脚本,并在合适的时机执行该脚本即可实现对进程监测、关闭和重启操作。 需要注意的是,脚本需要有足够的权限才能对进程进行操作,例如,root用户或者具有特定权限的用户。另外,根据具体情况,可能还需要设置定时任务或者监测进程状态的循环来实现持续的监测和操作。 ### 回答3: 为了实现Linux系统中进程的自动关闭和自动重启,可以编写一个脚本来实现这一功能。 首先,需要通过命令行或者脚本获取进程的PID(进程ID),可以使用命令`pgrep`或者`ps`搭配`grep`来实现。例如,使用`pgrep`命令查找进程名为"myprocess"的PID: ``` pid=$(pgrep myprocess) ``` 或者使用`ps`命令: ``` pid=$(ps -ef | grep myprocess | grep -v grep | awk '{print $2}') ``` 接下来,可以使用`kill`命令来关闭进程,例如: ``` kill $pid ``` 或者带有参数`-9`来强制关闭进程: ``` kill -9 $pid ``` 然后,在脚本中可以使用循环来检测进程是否关闭,可以使用`pgrep`命令或者检查进程是否存在于`/proc`目录下的方法。例如使用`pgrep`命令来判断进程是否存在: ``` while pgrep myprocess > /dev/null; do sleep 1 done ``` 或者检查进程是否存在于`/proc`目录下: ``` while [ -d "/proc/$pid" ]; do sleep 1 done ``` 最后,在循环结束后,可以使用脚本或者命令重启进程,例如: ``` ./myprocess.sh ``` 或者 ``` myprocess & ``` 综上所述,可以编写一个包含以上步骤的脚本,来实现Linux系统中进程的自动关闭和自动重启功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值