钉钉监控服务器进程

本文介绍了一个使用Python编写的简单程序,该程序能够监控指定的服务进程(如httpd和sshd),并在这些进程意外停止时自动尝试重启。此外,通过发送消息到预先设定的webhook地址来通知管理员有关进程的状态变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python3
# -*- conding: utf-8 -*-
import os
import time
import requests
import json
import psutil
#CPU,MEM,NET,IO,DISK,SERVER,PROCESS

url = '输入你的机器人webhook'
time_now = time.strftime('%Y-%M-%d %H:%M:$S',time.localtime(time.time()))

monitor_name = {'httpd','sshd'}
#预监控服务
monitor_map = {
    'httpd':'systemctl start httpd'
}
while True:
    proc_dict = {}
    #PID:进程名
    proc_name = set()
    #进程名集合
    for p in psutil.process_iter(attrs=['pid','name']):
        #当前操作系统下所有进程名及进程ID
        proc_dict[p.info['pid']] = p.info['name']
        proc_name.add(p.info['name'])

    proc_stop = monitor_name - proc_name
    #未开启的进程
    if proc_stop:
        for p in proc_stop:
            p_status = '停止!'
            p_name = p

            data = {
            "msgtype":"markdown",
            "markdown":{
            "title":"监控讯息",
            "text":"#### %s\n" % time_now +
             "> #### 服务名:%s \n\n" % p_name +
             "> #### 状态: %s \n" % p_status +
             "> #### 正在尝试启动"
                }
            }
            '''
            "at":{
                "atMobiles":[
                    "152xxxxxxxx",
                ],
                "isAtAll":True
                }
             '''
            headers = {'Content-Type':'application/json;charset=utf-8'}
            send_data = json.dumps(data).encode('utf-8')
            requests.post(url=url,data=send_data,headers=headers)
            #post提交数据

            os.system(monitor_map[p])
            proc_name = set()
            for p1 in psutil.process_iter(attrs=['pid','name']):
                proc_name.add(p1.info['name'])
            if p in proc_name:
                p_status = '启动!'
                p_name = p
                data = {
                "msgtype":"markdown",
                "markdown":{
                "title":"监控讯息",
                "text":"#### %s\n" % time_now +
                 "> #### 服务名:%s \n\n" % p_name +
                 "> #### 状态: %s \n" % p_status +
                 "> #### 重启成功!"
                    }
                }
                headers = {'Content-Type':'application/json;charset=utf-8'}
                send_data = json.dumps(data).encode('utf-8')
                requests.post(url=url,data=send_data,headers=headers)
            else:
                p_status = '停止!'
                p_name = p
                data = {
                "msgtype":"markdown",
                "markdown":{
                "title":"监控讯息",
                "text":"#### %s\n" % time_now +
                 "> #### 服务名:%s \n\n" % p_name +
                 "> #### 状态: %s \n" % p_status +
                 "> #### 启动失败!"
                    }
                }
                headers = {'Content-Type':'application/json;charset=utf-8'}
                send_data = json.dumps(data).encode('utf-8')
                requests.post(url=url,data=send_data,headers=headers)

    else:
        for p in monitor_name:
            p_status = '运行中!'
            p_name = p
            data = {
            "msgtype":"markdown",
            "markdown":{
            "title":"监控讯息",
            "text":"#### %s\n" % time_now +
             "> #### 服务名:%s \n\n" % p_name +
             "> #### 状态: %s \n" % p_status +
             "> #### 进程正常!"
                }
            }
            headers = {'Content-Type':'application/json;charset=utf-8'}
            send_data = json.dumps(data).encode('utf-8')
            requests.post(url=url,data=send_data,headers=headers)
    time.sleep(2)
### 配置Prometheus监控以在服务器密码即将过期时通过钉钉机器人发送告警通知 #### 创建自定义钉钉机器人 为了使Prometheus能够向指定的钉钉群组发送告警信息,需创建一个自定义钉钉机器人。具体操作是在目标钉钉聊天窗口内点击右上角图标选择添加机器人选项,并按照指引完成设置过程[^2]。 #### 编写Prometheus告警规则 针对Linux系统中的账户密码到期情况,可利用`passwd`命令配合脚本定期检查各用户的密码有效期,并将此数据作为指标暴露给Prometheus抓取。编写相应的PromQL表达式来设定触发条件,比如剩余天数小于等于7天即发出警告: ```yaml groups: - name: example rules: - alert: PasswordExpiringSoon expr: user_password_expiration_days < 7 for: 0m labels: severity: warning annotations: summary: "User password will expire soon (instance {{ $labels.instance }})" description: "{{ $labels.user }}'s password on instance {{ $labels.instance }} expires within a week." ``` 上述YAML片段展示了如何定义一条名为PasswordExpiringSoon的告警规则,当检测到用户密码将在一周之内过期时会激活这条告警[^1]。 #### 整合钉钉Webhook至Alertmanager配置 为了让Prometheus产生的告警最终能传递到钉钉群里,在Alertmanager中加入接收者配置项并将之前获得的webhook URL填入其中。以下是部分alertmanager.yml模板示例: ```yaml route: receiver: 'dingtalk-notifications' receivers: - name: 'dingtalk-notifications' webhook_configs: - url: 'https://oapi.dingtalk.com/robot/send?access_token=your_access_token_here&sign=your_sign_here' send_resolved: true ``` 这里需要注意替换实际取得的安全签名(sign)与访问令牌(access_token),确保URL指向正确的自定义机器人地址。 #### 实现热更新机制保持服务连续性 每当调整了Prometheus或Alertmanager的相关配置之后,应当采取适当的方式让更改生效而不中断现有监测任务。对于Prometheus而言,推荐的做法是执行HTTP POST请求至特定路径从而触发热加载流程;而对于Alertmanager,则可以直接重启进程使其读取最新的配置文件版本[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值