python+crontab定时监控某个进程并钉钉告警

一时兴起就写了,头次用这个模块,入了坑,最后度娘度娘拯救了我,差点爬不起来。

下面来整理下我的误区:

  1. os.system(CMD) 返回的是shell执行是否成功返回的值
  2. os.popen(CMD) 返回的是shell执行显示的值,返回的是内存中的编码
  3. os.popen(CMD).read() 执行命令并读取内存中的数据

直接上代码

# -*- coding: utf-8 -*-
import os
import requests
import json
def dingTalk(msg_text):
    url = "https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx"
    headers = {
        "Content-Type": "application/json"
            }
    data = {
     "msgtype": "markdown",
     "markdown": {
         "title": "Seriver Process Monitor Alert",
         "text": msg_text
     },
      "at": {
          "atMobiles": [
              "12345678900"  #手机号
          ],
          "isAtAll": False    #通知全部成员
      }
    }
    json_data = json.dumps(data)
    requests.post(url=url, data=json_data, headers=headers)
def Check_Process():
        Stat_Laravel_Zz = " ps -A -ostat,ppid,pid,cmd | grep laravel-echo-server | grep -v grep | awk '{print $1}'"
        Kill_Laravel_Zz = " ps -A -ostat,ppid,pid,cmd | grep laravel-echo-server | grep -v grep | awk '{print $2}' | xargs kill -9 "
        Laravel_echo_server = 'ps -ef | grep -v grep |grep laravel-echo-server|wc -l'
        Start_Laravel_echo = 'cd /www/wwwroot/kulianOA2.0/;/usr/local/nodejs/bin/laravel-echo-server start&>>/python_shell_script/laravel-echo-server.log&'
        if os.popen(Stat_Laravel_Zz).read() != 'Zz':
            if os.popen(Laravel_echo_server).read() < str(1):
                os.system(Start_Laravel_echo)
                number_process = os.popen(Laravel_echo_server)
                process_null_msg = "### 当前Laravel-echo-server进程少于0\n启动中......\n### 已启动,当前Laravel-echo-server进程数有%s"% str(number_process) + '个\n'
                dingTalk(process_null_msg)

        else:
            os.system(Kill_Laravel_Zz)
            os.system(Start_Laravel_echo)
            number_process = os.popen(Laravel_echo_server)
            process_null_msg = "### 当前Laravel-echo-server有僵尸进程\nKILL Laravel-echo-server......\n ### 已启动,当前Laravel-echo-server进程数有%s"% str(number_process) + '个\n'
            dingTalk(process_null_msg)
if __name__ == "__main__":
    Check_Process()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容