以下是一个使用Python监控CentOS 7系统日志中关键词"ERROR"并通过钉钉机器人告警的示例代码:

import requests
import subprocess

# 钉钉机器人的webhook地址
webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=YOUR_ACCESS_TOKEN"

# 监控日志文件路径
log_file = "/var/log/messages"

# 监控关键词
keyword = "ERROR"

# 定义函数,发送钉钉机器人告警消息
def send_dingding_alert(content):
    headers = {"Content-Type": "application/json"}
    data = {
        "msgtype": "text",
        "text": {
            "content": content
        }
    }
    response = requests.post(webhook_url, json=data, headers=headers)
    if response.status_code == 200:
        print("发送钉钉消息成功")
    else:
        print("发送钉钉消息失败")

# 执行命令,实时查看日志文件中是否包含关键词
p = subprocess.Popen(["tail", "-F", log_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(p.stdout.readline, b''):
    if keyword in line.decode("utf-8"):
        send_dingding_alert("系统日志中出现关键词 {} :{}".format(keyword, line.decode("utf-8").strip()))

注意替换代码中的YOUR_ACCESS_TOKEN为你的钉钉机器人的access_token。

运行以上代码后,它将实时监控/var/log/messages日志文件中是否包含关键词"ERROR",如果出现关键词则会发送告警消息到钉钉机器人。你可以根据需要修改日志文件路径和关键词

请给我监控centos7系统日志中关键词ERROR并钉钉机器人告警的python代码

原文地址: https://www.cveoy.top/t/topic/hCQY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录